search
HomeDatabaseMysql TutorialJDBC数据库的使用操作总结_MySQL

JDBC数据库的使用操作总结_MySQL

Jun 01, 2016 pm 01:24 PM
javainterfaceDatabase operationsprogrammer

bitsCN.com

JDBC是一组能够执行SQL语句的API

由于传统的数据库操作方式需要程序员掌握各个不同的数据库的API,极其不便

因此java定义了JDBC这一标准的接口和类,为程序员操作数据库提供了统一的方式

JDBC的操作方式比较单一,由五个流程组成:

1.通过数据库厂商提供的JDBC类库向DriverManager注册数据库驱动

2.使用DriverManager提供的getConnection()方法连接到数据库

3.通过数据库的连接对象的createStatement方法建立SQL语句对象

4.执行SQL语句,并将结果集合返回到ResultSet中

5.使用while循环读取结果

6.关闭数据库资源

下面来看看具体操作Mysql数据库的方法


准备工作

首先我们需要建立一个数据库和一张简单的表

mysql> create database person;
Query OK, 1 row affected (0.00 sec)

mysql> use person;
Database changed
mysql> create table student(
    -> id int,
    -> name varchar(20),
    -> birth year
    -> ) default charset=utf8;
Query OK, 0 rows affected (0.10 sec)

然后往里面插入几条数据

mysql> insert into student values
    -> (1,'张三',1990),
    -> (2,'李四',1991),
    -> (3,'王五',1992);
Query OK, 3 rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0

这样一张简单的表就建好了

mysql> select * from student;
+------+--------+-------+
| id   | name   | birth |
+------+--------+-------+
|    1 | 张三   |  1990 |
|    2 | 李四   |  1991 |
|    3 | 王五   |  1992 |
+------+--------+-------+
 rows in set (0.00 sec)

接下来,去mysql官网下载数据库连接器这个包

其中这个包里面含有一份文档,里面列举了基本的使用方法,可以参考

我们的操作也是按照这份文档中的内容进行,然后最主要的地方就是导入这个jar包

为了操作方便,这里使用eclipse来导入

右键项目-->构件路径-->添加外部归档,添加好了之后如下所示

现在我们正式开始使用java来操作mysql数据库

JDBC操作实例1:最简单的查询操作

import java.sql.*;

public class Demo {
    //为了代码紧凑性,暂时抛出所有异常
    public static void main(String[] args) throws Exception {
        //注册数据库驱动
        Class.forName("com.mysql.jdbc.Driver");
        //建立数据库连接
        //参数一:jdbc:mysql//地址:端口/数据库,参数二:用户名,参数三:密码
        Connection conn = DriverManager.getConnection
                ("jdbc:mysql://localhost:3306/person","root","admin");
        //创建SQL语句
        Statement st = conn.createStatement();
        //执行语句,返回结果
        ResultSet rt = st.executeQuery("show tables");
        //循环取出结果
        while(rt.next()) {
            //获取字段
            System.out.println(rt.getString("Tables_in_person"));
        }
        //关闭资源,最先打开的最后关
        rt.close();
        st.close();
        conn.close();
    }
}

运行结果:student

如此便可执行show tables语句查询出当前数据库含有多少张表

其中rt.getString()方法是获取字段,这点需要注意

关闭资源的方式也与以往相反

不过,上面的操作方式灵活性不大,并且不严谨


实例2:优化的查询操作

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/person";
        String user = "root";
        String pwd = "admin";
        String sql = "select * from student";

        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pwd);
            st = conn.createStatement();
            //执行查询语句,另外也可以用execute(),代表执行任何SQL语句
            rs = st.executeQuery(sql);
            while(rs.next()) {
                System.out.println(rs.getObject(1) + "  " +
                        rs.getObject(2) + "  " + rs.getInt("birth"));
            }
        //分别捕获异常
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                //判断资源是否存在
                if(rs != null) {
                    rs.close();
                    //显示的设置为空,提示gc回收
                    rs = null;
                }
                if(st != null) {
                    st.close();
                    st = null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }   
        }
    }
}

运行结果:

这里把异常给分别捕获了,并且相关的字符串全部用变量定义

需要注意下循环取出数据里面的getInt()方法,此处必须知道类型和字段才能取出

如果不知道可以使用getObject(1)取出第一列,getObject(2)取出第二列,以此类推

实例3:自定义变量插入到数据库

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo {
    public static void main(String[] args) {
        //参数检查
        if (args.length != 3) {
            System.out.println("参数形式不对");
            System.exit(0);
        }
        String id = args[0];
        String name = args[1];
        String birth = args[2];
        String sql = "insert into student values(" + id + ",'" + name +
                "'," + "'" + birth + "')";
        System.out.println(sql);

        String url = "jdbc:mysql://localhost:3306/person";
        String user = "root";
        String pwd = "admin";

        Connection conn = null;
        Statement st = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pwd);
            st = conn.createStatement();
            //注意,此处是excuteUpdate()方法执行
            st.executeUpdate(sql);       
        //分别捕获异常
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(st != null) {
                    st.close();
                    st = null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }   
        }
    }
}

运行结果:

这里运行需要设置自变量,窗口中右键-->运行方式-->运行配置

然后在自变量里面写4 susan 1993,我没有写中文,因为产生乱码,目前还不清楚原因

需要注意的是,执行插入的SQL语句比较难写,最好是打印出SQL语句用以检查

实例4:PreparedStatement应用

从上面的Demo可以看到,插入数据的时候,SQL操作相当不便

这里可以使用PreparedStatement对象来简化SQL语句的建立

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Demo {

    public static void main(String[] args) {
        if (args.length != 3) {
            System.out.println("参数形式不对");
            System.exit(0);
        }
        String id = args[0];
        String name = args[1];
        String birth = args[2];

        String url = "jdbc:mysql://localhost:3306/person";
        String user = "root";
        String pwd = "admin";

        Connection conn = null;
        //声明PreparedStatement对象的引用
        PreparedStatement pst = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pwd);
            //使用?代替变量
            pst = conn.prepareStatement("insert into student values (?,?,?)");
            //给指定参数的位置设定变量
            pst.setString(1, id);
            pst.setString(2, name);
            pst.setString(3, birth);
            pst.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(pst != null) {
                    pst.close();
                    pst = null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }   
        }
    }
}

运行结果:

实例5:Batch批处理

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo {

    public static void main(String[] args) {

        String url = "jdbc:mysql://localhost:3306/person";
        String user = "root";
        String pwd = "admin";

        Connection conn = null;
        Statement st = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pwd);
            st = conn.createStatement();
            //添加批处理
            st.addBatch("insert into student values(6,'Jerry','1995')");
            st.addBatch("insert into student values(7,'Greg','1996')");
            st.addBatch("insert into student values(8,'Ryan','1997')");
            //执行批处理
            st.executeBatch();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(st != null) {
                    st.close();
                    st = null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }   
        }
    }
}

运行结果:

批处理比较简单,只需先建立Statement对象,然后逐个添加批处理即可

最后使用executeBatch()方法执行批处理

此外,PreparedStatement对象也可以使用批处理

PreparedStatement ps = conn.prepareStatement("insert into student values(?,?,?)");
ps.setInt(1,8);
ps.setString(2,"GG");
ps.setString(3,"1996");
ps.addBatch();
ps.executeBatch();

实例6:Transaction事务处理

事务处理是要求sql以单元的形式更新数据库,要求其确保一致性

如银行的转账业务,一方转出后,另一方则增加

如果出现异常,那么所有的操作则会回滚

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo {

    public static void main(String[] args) {

        String url = "jdbc:mysql://localhost:3306/person";
        String user = "root";
        String pwd = "admin";

        Connection conn = null;
        Statement st = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pwd);
            //取消自动提交
            conn.setAutoCommit(false);
            st = conn.createStatement();
            st.addBatch("insert into student values(6,'Jerry','1995')");
            st.addBatch("insert into student values(7,'Greg','1996')");
            st.addBatch("insert into student values(8,'Ryan','1997')");
            st.executeBatch();
            //提交后设置自动提交
            conn.commit();
            conn.setAutoCommit(true);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();

        } catch (SQLException e) {
            e.printStackTrace();

            if(conn != null) {
                try {
                    //出现异常则回滚操作,然后设置自动提交
                    conn.rollback();
                    conn.setAutoCommit(true);
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
        } finally {
            try {
                if(st != null) {
                    st.close();
                    st = null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }   
        }
    }
}

运行结果:

bitsCN.com
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the differences in syntax between MySQL and other SQL dialects?What are the differences in syntax between MySQL and other SQL dialects?Apr 27, 2025 am 12:26 AM

MySQLdiffersfromotherSQLdialectsinsyntaxforLIMIT,auto-increment,stringcomparison,subqueries,andperformanceanalysis.1)MySQLusesLIMIT,whileSQLServerusesTOPandOracleusesROWNUM.2)MySQL'sAUTO_INCREMENTcontrastswithPostgreSQL'sSERIALandOracle'ssequenceandt

What is MySQL partitioning?What is MySQL partitioning?Apr 27, 2025 am 12:23 AM

MySQL partitioning improves performance and simplifies maintenance. 1) Divide large tables into small pieces by specific criteria (such as date ranges), 2) physically divide data into independent files, 3) MySQL can focus on related partitions when querying, 4) Query optimizer can skip unrelated partitions, 5) Choosing the right partition strategy and maintaining it regularly is key.

How do you grant and revoke privileges in MySQL?How do you grant and revoke privileges in MySQL?Apr 27, 2025 am 12:21 AM

How to grant and revoke permissions in MySQL? 1. Use the GRANT statement to grant permissions, such as GRANTALLPRIVILEGESONdatabase_name.TO'username'@'host'; 2. Use the REVOKE statement to revoke permissions, such as REVOKEALLPRIVILEGESONdatabase_name.FROM'username'@'host' to ensure timely communication of permission changes.

Explain the differences between InnoDB and MyISAM storage engines.Explain the differences between InnoDB and MyISAM storage engines.Apr 27, 2025 am 12:20 AM

InnoDB is suitable for applications that require transaction support and high concurrency, while MyISAM is suitable for applications that require more reads and less writes. 1.InnoDB supports transaction and bank-level locks, suitable for e-commerce and banking systems. 2.MyISAM provides fast read and indexing, suitable for blogging and content management systems.

What are the different types of JOINs in MySQL?What are the different types of JOINs in MySQL?Apr 27, 2025 am 12:13 AM

There are four main JOIN types in MySQL: INNERJOIN, LEFTJOIN, RIGHTJOIN and FULLOUTERJOIN. 1.INNERJOIN returns all rows in the two tables that meet the JOIN conditions. 2.LEFTJOIN returns all rows in the left table, even if there are no matching rows in the right table. 3. RIGHTJOIN is contrary to LEFTJOIN and returns all rows in the right table. 4.FULLOUTERJOIN returns all rows in the two tables that meet or do not meet JOIN conditions.

What are the different storage engines available in MySQL?What are the different storage engines available in MySQL?Apr 26, 2025 am 12:27 AM

MySQLoffersvariousstorageengines,eachsuitedfordifferentusecases:1)InnoDBisidealforapplicationsneedingACIDcomplianceandhighconcurrency,supportingtransactionsandforeignkeys.2)MyISAMisbestforread-heavyworkloads,lackingtransactionsupport.3)Memoryengineis

What are some common security vulnerabilities in MySQL?What are some common security vulnerabilities in MySQL?Apr 26, 2025 am 12:27 AM

Common security vulnerabilities in MySQL include SQL injection, weak passwords, improper permission configuration, and unupdated software. 1. SQL injection can be prevented by using preprocessing statements. 2. Weak passwords can be avoided by forcibly using strong password strategies. 3. Improper permission configuration can be resolved through regular review and adjustment of user permissions. 4. Unupdated software can be patched by regularly checking and updating the MySQL version.

How can you identify slow queries in MySQL?How can you identify slow queries in MySQL?Apr 26, 2025 am 12:15 AM

Identifying slow queries in MySQL can be achieved by enabling slow query logs and setting thresholds. 1. Enable slow query logs and set thresholds. 2. View and analyze slow query log files, and use tools such as mysqldumpslow or pt-query-digest for in-depth analysis. 3. Optimizing slow queries can be achieved through index optimization, query rewriting and avoiding the use of SELECT*.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.