使用JDBC操作MySQL数据库

什么是JDBC
JDBC是Java数据库连接,(Java Database Connectivity)的简称,是Java语言中用来规范客户端程序如何来访问关系型数据库的应用程序接口,提供了诸如增加,删除,修改,查询据库中数据的方法。

JDBC连接数据库的步骤
下面以MySQL为例,介绍一下JDBC连接数据库的步骤。
1.加载数据库驱动程序

    Class.forName(“com.mysql.jdbc.Driver”);

2.定义要连接数据库的连接地址URL,地址URL的格式为:jdbc:<子协议>:<子名称>

    String mysqlURL = “jdbc:mysql://localhost:port/dbName”;  

3.使用连接字符串获取连接对象

    Connection conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);

4.创建语句对象

    //创建一个statement语句对象
    Statement  smt = conn.createStatement();


    //创建预编译语句对象
    String SQL="SELECT * FROM EMP";
    PreparedStatement pst = conn.prepareStatement(SQL);


    //创建一个用于调用存储过程或函数的语句对象
    String SQL=“{call printQuitEmp(?,?)}”;
    CallableStatement cst = conn.prepareCall(SQL);

5.执行语句

Statement接口提供了3个方法执行sql语句,分别是executeQuery、executeUpdate和execute

executeQuery方法用于执行SELECT查询语句,并返回单个结果集,保存在ResultSet对象中

    Statement  smt = conn.createStatement();
    String SQL = "SELECT * FROM EMP";
    ResultSet rst = smt.executeQuery(SQL);

executeUpdate方法用于执行DML语句,包括INSERT,UPDATE和DELETE语句,返回值是一个整数。executeUpdate方法还可用于执行sql DDL语句,如CREATE TABLE, DROP TABLE等。此时返回值为0.

    Statement  smt = conn.createStatement();
    String SQL="INSERT INTO EMP VALUES(?,?,?,?,?,?,?,?)";
    int rst = smt.executeUpdate(SQL);

Execute方法既可以执行查询语句,也可以执行更新语句,常用于动态处理类型未知的SQL语句

6.返回结果集ResultSet对象

sql语句的执行的结果集保存在ResultSet对象,我们可以通过以下方式遍历此结果集。

    Statement  smt = conn.createStatement();
    String SQL = “SELECT * FROM EMP”;
    ResultSet rst = smt.executeQuery(SQL);
    while(rst.next()) {
        empno = rs.getString(1);
        ename = rs.getString(2);
        System.out.println(empno+”\t”+ename);
    }

7.关闭连接。

    rst.close();
    smt.close();
    conn.close();

数据表
假设现在有一个emp数据库,数据库里有一张EMP表,结构和数据如下:

    mysql> desc EMP;
    +----------+-------------+------+-----+---------+-------+
    | Field    | Type        | Null | Key | Default | Extra |
    +----------+-------------+------+-----+---------+-------+
    | EMPNO    | int(11)     | NO   | PRI | NULL    |       |
    | ENAME    | varchar(10) | YES  |     | NULL    |       |
    | JOB      | varchar(9)  | YES  |     | NULL    |       |
    | MGR      | int(11)     | YES  |     | NULL    |       |
    | HIREDATE | date        | YES  |     | NULL    |       |
    | SAL      | double      | YES  |     | NULL    |       |
    | COMM     | double      | YES  |     | NULL    |       |
    | DEPTNO   | int(11)     | YES  | MUL | NULL    |       |
    +----------+-------------+------+-----+---------+-------+
    8 rows in set (0.00 sec)

    mysql> select * from EMP;
    +-------+--------+-----------+------+------------+------+------+--------+
    | EMPNO | ENAME  | JOB       | MGR  | HIREDATE   | SAL  | COMM | DEPTNO |
    +-------+--------+-----------+------+------------+------+------+--------+
    |  7369 | SMITH  | CLERK     | 7902 | 1980-12-17 |  800 | NULL |     20 |
    |  7499 | ALLEN  | SALESMAN  | 7698 | 1981-02-20 | 1600 |  300 |     30 |
    |  7521 | WARD   | SALESMAN  | 7698 | 1981-02-22 | 1250 |  500 |     30 |
    |  7566 | JONES  | MANAGER   | 7839 | 1981-04-02 | 2975 | NULL |     20 |
    |  7654 | MARTIN | SALESMAN  | 7698 | 1981-09-28 | 1250 | 1400 |     30 |
    |  7698 | BLAKE  | MANAGER   | 7839 | 1981-05-01 | 2850 | NULL |     30 |
    |  7782 | CLARK  | MANAGER   | 7839 | 1981-06-09 | 2450 | NULL |     10 |
    |  7788 | SCOTT  | ANALYST   | 7566 | 1987-07-03 | 3000 | NULL |     20 |
    |  7839 | KING   | PRESIDENT | NULL | 1981-11-17 | 5000 | NULL |     10 |
    |  7844 | TURNER | SALESMAN  | 7698 | 1981-09-08 | 1500 |    0 |     30 |
    |  7876 | ADAMS  | CLERK     | 7788 | 1987-07-13 | 1100 | NULL |     20 |
    |  7900 | JAMES  | CLERK     | 7698 | 1981-12-03 |  950 | NULL |     30 |
    |  7902 | FORD   | ANALYST   | 7566 | 1981-12-03 | 3000 | NULL |     20 |
    |  7934 | MILLER | CLERK     | 7782 | 1981-01-23 | 1300 | NULL |     10 |
    +-------+--------+-----------+------+------------+------+------+--------+
    14 rows in set (0.00 sec)

完整案例
案例一:使用PrepareStatement执行DML操作

    import java.sql.*;
   
    public class Test {
        public static void main(String[] args) {
    
            final String DRIVER = "com.mysql.jdbc.Driver";
            final String URL = "jdbc:mysql://192.168.4.116:3306/test1?useUnicode=true&characterEncoding=utf8&useSSL=true";
            final String USERNAME = "root";
            final String PASSWORD = "root";
    
            Connection conn=null;
            PreparedStatement pst=null;
            int rst=0;
            String SQL="INSERT INTO EMP VALUES(?,?,?,?,?,?,?,?)";
    
            try {
                conn=DriverManager.getConnection(URL,USERNAME,PASSWORD);
                pst=conn.prepareStatement(SQL);
                pst.setObject(1,7998);
                pst.setObject(2,"WENDY");
                pst.setObject(3,"SALESMAN");
                pst.setObject(4,7698);
                pst.setObject(5,"1986-05-18");
                pst.setObject(6,2000);
                pst.setObject(7,0);
                pst.setObject(8,30);
                rst=pst.executeUpdate();
                System.out.println("成功插入"+rst+"条数据。");
    
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
    
                if(null!=pst){
                    try {
                        pst.close();
                    }catch (SQLException e){
                        System.out.println(e.getMessage());
                    }
                }
                if(null!=conn){
                    try {
                        conn.close();
                    }catch (SQLException e){
                        System.out.println(e.getMessage());
                    }
                }
    
            }
        }
    }        

运行结果如下:

    成功插入1条数据。

查询数据库,此时多了一条empno=7998的记录。

    mysql> select * from EMP;
    +-------+--------+-----------+------+------------+------+------+--------+
    | EMPNO | ENAME  | JOB       | MGR  | HIREDATE   | SAL  | COMM | DEPTNO |
    +-------+--------+-----------+------+------------+------+------+--------+
    |  7369 | SMITH  | CLERK     | 7902 | 1980-12-17 |  800 | NULL |     20 |
    |  7499 | ALLEN  | SALESMAN  | 7698 | 1981-02-20 | 1600 |  300 |     30 |
    |  7521 | WARD   | SALESMAN  | 7698 | 1981-02-22 | 1250 |  500 |     30 |
    |  7566 | JONES  | MANAGER   | 7839 | 1981-04-02 | 2975 | NULL |     20 |
    |  7654 | MARTIN | SALESMAN  | 7698 | 1981-09-28 | 1250 | 1400 |     30 |
    |  7698 | BLAKE  | MANAGER   | 7839 | 1981-05-01 | 2850 | NULL |     30 |
    |  7782 | CLARK  | MANAGER   | 7839 | 1981-06-09 | 2450 | NULL |     10 |
    |  7788 | SCOTT  | ANALYST   | 7566 | 1987-07-03 | 3000 | NULL |     20 |
    |  7839 | KING   | PRESIDENT | NULL | 1981-11-17 | 5000 | NULL |     10 |
    |  7844 | TURNER | SALESMAN  | 7698 | 1981-09-08 | 1500 |    0 |     30 |
    |  7876 | ADAMS  | CLERK     | 7788 | 1987-07-13 | 1100 | NULL |     20 |
    |  7900 | JAMES  | CLERK     | 7698 | 1981-12-03 |  950 | NULL |     30 |
    |  7902 | FORD   | ANALYST   | 7566 | 1981-12-03 | 3000 | NULL |     20 |
    |  7934 | MILLER | CLERK     | 7782 | 1981-01-23 | 1300 | NULL |     10 |
    |  7998 | WENDY  | SALESMAN  | 7698 | 1988-05-18 | 2000 |    0 |     30 |
    +-------+--------+-----------+------+------------+------+------+--------+

案例二:使用Statement执行查询操作

    import java.sql.*;
    
    public class Test {
        public static void main(String[] args) {
    
            final String DRIVER = "com.mysql.jdbc.Driver";
            final String URL = "jdbc:mysql://192.168.4.116:3306/test1?useUnicode=true&characterEncoding=utf8&useSSL=true";
            final String USERNAME = "root";
            final String PASSWORD = "root";
    
            Connection conn=null;
            Statement smt=null;
            ResultSet rst=null;
            String SQL="SELECT * FROM EMP";
    
            try {
                conn=DriverManager.getConnection(URL,USERNAME,PASSWORD);
                smt=conn.createStatement();
                rst=smt.executeQuery(SQL);
                if(null!=rst){
                    while (rst.next()){
                        System.out.print(rst.getObject(1)+"\t");
                        System.out.print(rst.getObject(2)+"\t");
                        System.out.print(rst.getObject(3)+"\t");
                        System.out.println(" ");
                    }
                }
    
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                if(null!=rst){
                    try {
                        rst.close();
                    }catch (SQLException e){
                        System.out.println(e.getMessage());
                    }
                }
                if(null!=smt){
                    try {
                        smt.close();
                    }catch (SQLException e){
                        System.out.println(e.getMessage());
                    }
                }
                if(null!=conn){
                    try {
                        conn.close();
                    }catch (SQLException e){
                        System.out.println(e.getMessage());
                    }
                }
    
            }
        }
    }

运行结果如下:

    7369	SMITH	CLERK	 
    7499	ALLEN	SALESMAN	 
    7521	WARD	SALESMAN	 
    7566	JONES	MANAGER	 
    7654	MARTIN	SALESMAN	 
    7698	BLAKE	MANAGER	 
    7782	CLARK	MANAGER	 
    7788	SCOTT	ANALYST	 
    7839	KING	PRESIDENT	 
    7844	TURNER	SALESMAN	 
    7876	ADAMS	CLERK	 
    7900	JAMES	CLERK	 
    7902	FORD	ANALYST	 
    7934	MILLER	CLERK	 
    7998	WENDY	SALESMAN	

你可能感兴趣的:(MySQL,mysql,java)