JDBC笔记

简介

  JDBC是Java规定的访问数据库的API,目前主流的数据库都支持JDBC。使用JDBC访问不同的数据库时需要安装不同的驱动。

  JDBC定义了数据库的链接,SQL语句的执行以及查询结果集的遍历等等。JDBC把这些操作定义为接口,位于包java.sql下面,如果java.sql.Connection、java.sql.Statement、java.sql.ResultSet等。

  各个数据库提供商在自己的JDBC驱动中实现了这些接口。

JDBC连接数据库的一般步骤

  1.注册驱动

  2.获取连接

  3.获取Statement

  4.执行SQL并返回结果集

  5.遍历结果集显示数据

  6.释放连接

package com.sean;

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

import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;

public class TestJDBC {
    public static final String PC_NAME = "pc_name";
    public static final String IP = "ip";

    public static void main(String[] args) {
        Statement stmt = null;
        Connection conn = null;
        ResultSet rs = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");//首先注册mysql驱动
            String url = "jdbc:mysql://localhost/sean?user=root&password=root";
            conn = DriverManager.getConnection(url);//连接mysql数据库

            String query = "select * from pc_ip_list";
            stmt = (Statement) conn.createStatement();//获取Statement
            rs = (ResultSet) stmt.executeQuery(query);//执行查询语句

            while (rs.next()) {//遍历结果集
                System.out.print(rs.getString(PC_NAME) + " "+ rs.getString(IP) + "
");
            }

        } 
        catch (ClassNotFoundException e) {
              System.out.println("驱动程序未找到,请加入mysql.jdbc的驱动包。。。");
            e.printStackTrace();
        }
        catch (SQLException e) {
            System.out.println("执行SQL语句过程中出现了错误。。。");
            e.printStackTrace();
        } finally {//释放连接
            try {
                //最后打开的最新关闭
                if (rs != null) {
                    rs.close();
                }
                
                if (stmt != null) {
                    stmt.close();
                }
                
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

数据库的连接URL

  数据库                          连接URL                                          

  MySQL             jdbc:mysql://localhost:3306/db_name        

  Oracle              jdbc:oracle:thin:@localhost:1521:db_name

  DB2                 jdbc:db2://localhost:6789/db

JDBC基本操作

  增删改基本流程与上面的查询一样,只不过在执行sql语句的时候使用的是Statement的excuteUpdate方法,执行结果返回受影响的记录条数。

String insertSql = "insert into sean values ('pc1', '127.0.0.1')";
String deleteSql = "delete from sean where name = 'pc1'";

stmt.executeUpdate(insertSql);
stmt.executeUpdate(deleteSql);

使用PreparedStatement

  上面的例子中增删改查操作都是通过Statement对象实现的,使用Statement是最简单的方式。除此之外还可使用PreparedSattement,它继承了Statement,最大区别是

PreparedStatement可以使用参数,也就是(?)号。PreparedStatement可以使用不完整的SQL语句,空缺的部分使用问号(?)代替,直到执行前设置进去。从此便可以避免上面构造sql语句时所带来的种种不方便(如加各种单引号'')。

package com.sean;

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

import com.mysql.jdbc.PreparedStatement;

public class TestJDBC2 {

    public static void main(String args[]){
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/sean?user=root&password=root");
            pstmt = (PreparedStatement) conn.prepareStatement("insert into sean values (?,?)");//获取PreparedStatement
            pstmt.setString(1, "pstm1");//设置第一个?对应的值
            pstmt.setString(2, "192.168.168.168");//设置第二个?对应的值
            
            int count = pstmt.executeUpdate();//执行sql语句
            if (count > 0){
                System.out.print("excute success count = " + count);
            }
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (pstmt != null){
                    pstmt.close();
                }
                
                if (conn != null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        
    }
}

Statement与PreparedStatement的区别

  选择PreparedStatement还是Statement取决于你要怎么使用它们。对于只执行一次的SQL语句选择Statement是最好的. 相反, 
如果SQL语句被多次执行选用PreparedStatement是最好的。

  PreparedStatement: 数据库会对sql语句进行预编译,下次执行相同的sql语句时,数据库端不会再进行预编译了,而直接用数据库的缓冲区,提高数据访问的效率(但尽量采用使用?号的方式传递参数),如果sql语句只执行一次,以后不再复用。    从安全性上来看,PreparedStatement是通过?来传递参数的,避免了拼sql而出现sql注入的问题,所以安全性较好。在开发中,推荐使用 PreparedStatement。

  PreparedStatement的第一次执行消耗是很高的。它的性能体现在后面的重复执行。

Statement批处理SQL

package com.sean;

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

import com.mysql.jdbc.Statement;

public class TestBatch1 {
    public static void main(String[] args) {
        Statement stmt = null;
        Connection conn = null;
        
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/sean?user=root&password=root");
            stmt = (Statement) conn.createStatement();
            
            for (int i = 0; i < 5; ++i){
                String insertSql = "insert into sean values ('pc', '192.168.1.1')";
                System.out.println(insertSql);
                stmt.addBatch(insertSql);//添加语句到batch
            }
            int[] result = stmt.executeBatch();//执行batch
            
            for (int i = 0; i < result.length; ++i){
                System.out.println("result" + i + " = " + result[i]);//打印每一条sql语句执行的结果
            }
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        finally{
            try {
                if (stmt != null){
                    stmt.close();
                }
                
                if (conn != null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

PreparedStatement批处理SQL

package com.sean;

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

import com.mysql.jdbc.PreparedStatement;

public class TestBatch2 {

    public static void main(String args[]){
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/sean?user=root&password=root");
            pstmt = (PreparedStatement) conn.prepareStatement("insert into sean values (?,?)");//获取PreparedStatement
            
            for (int i = 0; i < 5; i++){
                pstmt.setString(1, "batch2");//设置第一个?对应的值
                pstmt.setString(2, "188.168.168.168");//设置第二个?对应的值
                pstmt.addBatch();//添加到batch
            }
            
            int[] result = pstmt.executeBatch();//批量执行sql语句
            for (int i = 0; i < result.length; ++i){
                System.out.println("result" + i + " = " + result[i]);//打印每一条sql语句执行的结果
            }
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (pstmt != null){
                    pstmt.close();
                }
                
                if (conn != null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        
    }
}
原文地址:https://www.cnblogs.com/hlb430/p/4382623.html