关于java:JDBC和数据库连接池

26次阅读

共计 39979 个字符,预计需要花费 100 分钟才能阅读完成。

文章和代码曾经归档至【Github 仓库:https://github.com/timerring/java-tutorial】或者公众号【AIShareLab】回复 java 也可获取。

JDBC 概述

根本介绍

  1. JDBC 为拜访不同的数据库提供了对立的接口,为使用者屏蔽了细节问题。
  2. Java 程序员应用 JDBC, 能够连贯任何提供了 JDBC 驱动程序的数据库系统,从而实现对数据库的各种操作。
  3. JDBC 的基本原理图[重要!]

模仿 JDBC

package com.hspedu.jdbc.myjdbc;

/**
 * 咱们规定的 jdbc 接口(办法)
 */
public interface JdbcInterface {

    // 连贯
    public Object getConnection() ;
    //crud
    public void crud();
    // 敞开连贯
    public void close();}
package com.hspedu.jdbc.myjdbc;

/**
 * mysql 数据库实现了 jdbc 接口 [模仿]【mysql 厂商开发】*/
public class MysqlJdbcImpl implements  JdbcInterface{
    @Override
    public Object getConnection() {System.out.println("失去 mysql 的连贯");
        return null;
    }

    @Override
    public void crud() {System.out.println("实现 mysql 增删改查");
    }

    @Override
    public void close() {System.out.println("敞开 mysql 的连贯");
    }
}
package com.hspedu.jdbc.myjdbc;

/**
 * @author 韩顺平
 * @version 1.0
 * 模仿 oracle 数据库实现 jdbc
 */
public class OracleJdbcImpl implements  JdbcInterface {
    @Override
    public Object getConnection() {System.out.println("失去 oracle 的连贯 降级");
        return null;
    }

    @Override
    public void crud() {System.out.println("实现 对 oracle 的增删改查");
    }

    @Override
    public void close() {System.out.println("敞开 oracle 的连贯");
    }
}
package com.hspedu.jdbc.myjdbc;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import java.util.Scanner;
public class TestJDBC {public static void main(String[] args) throws Exception {
        // 实现对 mysql 的操作
        JdbcInterface jdbcInterface = new MysqlJdbcImpl();
        jdbcInterface.getConnection(); // 通过接口来调用实现类[动静绑定]
        jdbcInterface.crud();
        jdbcInterface.close();


        // 实现对 oracle 的操作
        System.out.println("==============================");
        jdbcInterface = new OracleJdbcImpl();
        jdbcInterface.getConnection(); // 通过接口来调用实现类[动静绑定]
        jdbcInterface.crud();
        jdbcInterface.close();}
}

JDBC 带来的益处

如果 Java 间接拜访数据库(示意图)

JDBC 带来的益处(示意图)

阐明:JDBC 是 Java 提供一套用于数据库操作的接口 APl, Java 程序员只须要面向这套接口编程即可。不同的数据库厂商, 须要针对这套接口, 提供不同实现。

JDBC API 是一系列的接口,它对立和标准了应用程序与数据库的连贯、执行 SQL 语句,并到失去返回后果等各类操作, 相干类和接口在 java.sql 与 javax.sql 包中

JDBC 疾速入门

JDBC 程序编写步骤

  1. 注册驱动–加载 Driver 类
  2. 获取连贯–失去 Connection(java 程序和数据库之间的连贯)
  3. 执行增删改查–发送 SQL 给 mysql 执行
  4. 开释资源–敞开相干连贯

JDBC 第一个程序

通过 jdbc 对表 actor 进行增加,删除和批改操作

package com.hspedu.jdbc;

import com.mysql.jdbc.Driver;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 这是第一个 Jdbc 程序,实现简略的操作
 */
public class Jdbc01 {public static void main(String[] args) throws SQLException {

        // 前置工作:在我的项目下创立一个文件夹比方 libs
        // 将 mysql.jar 拷贝到该目录下,点击 add to project .. 退出到我的项目中
        //1. 注册驱动
        Driver driver = new Driver(); // 创立 driver 对象

        //2. 失去连贯
        //(1) jdbc:mysql:// 规定好示意协定,通过 jdbc 的形式连贯 mysql
        //(2) localhost 主机,能够是 ip 地址
        //(3) 3306 示意 mysql 监听的端口
        //(4) hsp_db02 连贯到 mysql dbms 的哪个数据库
        //(5) mysql 的连贯实质就是后面学过的 socket 连贯
        String url = "jdbc:mysql://localhost:3306/hsp_db02";
        // 将 用户名和明码放入到 Properties 对象
        Properties properties = new Properties();
        // 阐明 user 和 password 是规定好,前面的值依据理论状况写
        properties.setProperty("user", "root");// 用户
        properties.setProperty("password", "hsp"); // 明码
        Connection connect = driver.connect(url, properties);

        //3. 执行 sql
        //String sql = "insert into actor values(null,' 刘德华 ',' 男 ','1970-11-11','110')";
        //String sql = "update actor set name=' 周星驰 'where id = 1";
        String sql = "delete from actor where id = 1";
        //statement 用于执行动态 SQL 语句并返回其生成的后果的对象
        Statement statement = connect.createStatement();
        int rows = statement.executeUpdate(sql); // 如果是 dml 语句,返回的就是影响行数

        System.out.println(rows > 0 ? "胜利" : "失败");

        //4. 敞开连贯资源
        statement.close();
        connect.close();}
}

获取数据库连贯 5 种形式

形式 1

    // 形式 1
    @Test
    public void connect01() throws SQLException {Driver driver = new Driver(); // 创立 driver 对象
        String url = "jdbc:mysql://localhost:3306/hsp_db02";
        // 将 用户名和明码放入到 Properties 对象
        Properties properties = new Properties();
        // 阐明 user 和 password 是规定好,前面的值依据理论状况写
        properties.setProperty("user", "root");// 用户
        properties.setProperty("password", "hsp"); // 明码
        Connection connect = driver.connect(url, properties);
        System.out.println(connect);
    }

形式 2

    // 形式 2
    @Test
    public void connect02() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
        // 应用反射加载 Driver 类 , 动静加载,更加的灵便,缩小依赖性(把 forName 后的信息放在配置文件上更加不便)Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
        Driver driver = (Driver)aClass.newInstance();

        String url = "jdbc:mysql://localhost:3306/hsp_db02";
        // 将 用户名和明码放入到 Properties 对象
        Properties properties = new Properties();
        // 阐明 user 和 password 是规定好,前面的值依据理论状况写
        properties.setProperty("user", "root");// 用户
        properties.setProperty("password", "hsp"); // 明码

        Connection connect = driver.connect(url, properties);
        System.out.println("形式 2 =" + connect);
    }

形式 3

应用 DriverManager 代替 driver 进行对立治理

// 形式 3 应用 DriverManager 代替 driver 进行对立治理
@Test
public void connect03() throws IllegalAccessException, InstantiationException, ClassNotFoundException, SQLException {

    // 应用反射加载 Driver
    Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
    Driver driver = (Driver) aClass.newInstance();

    // 创立 url 和 user 和 password
    String url = "jdbc:mysql://localhost:3306/hsp_db02";
    String user = "root";
    String password = "hsp";

    DriverManager.registerDriver(driver);// 注册 Driver 驱动

    Connection connection = DriverManager.getConnection(url, user, password);
    System.out.println("第三种形式 =" + connection);
}

形式 4

// 形式 4: 应用 Class.forName 主动实现注册驱动,简化代码
// 这种形式获取连贯是应用的最多,举荐应用
@Test
public void connect04() throws ClassNotFoundException, SQLException {
    // 应用反射加载了 Driver 类
    // 在加载 Driver 类时,实现注册
    /*
        源码: 1. 动态代码块,在类加载时,会执行一次.
        2. DriverManager.registerDriver(new Driver());
        3. 因而注册 driver 的工作曾经实现
        static {
            try {DriverManager.registerDriver(new Driver());
            } catch (SQLException var1) {throw new RuntimeException("Can't register driver!");
            }
        }
     */
    Class.forName("com.mysql.jdbc.Driver");

    // 创立 url 和 user 和 password
    String url = "jdbc:mysql://localhost:3306/hsp_db02";
    String user = "root";
    String password = "hsp";
    Connection connection = DriverManager.getConnection(url, user, password);

    System.out.println("第 4 种形式~" + connection);

}
  1. mysqL 驱动 5.1.6 能够无需 CLass . forName(“com.mysql.jdbc.Driver”);
  2. 从 jdk1.5 当前应用了 jdbc4, 不再须要显示调用 class.forName()注册驱动而是主动调用驱动 jar 包下 META-INF\servicesViava.sql.Driver 文本中的类名称去注册
  3. 倡议还是写上 CLass . forName(“com.mysql.jdbc.Driver”), 更加明确

形式 5

// 形式 5 , 在形式 4 的根底上改良,减少配置文件,让连贯 mysql 更加灵便
@Test
public void connect05() throws IOException, ClassNotFoundException, SQLException {

    // 通过 Properties 对象获取配置文件的信息
    Properties properties = new Properties();
    properties.load(new FileInputStream("src\\mysql.properties"));
    // 获取相干的值
    String user = properties.getProperty("user");
    String password = properties.getProperty("password");
    String driver = properties.getProperty("driver");
    String url = properties.getProperty("url");

    Class.forName(driver);// 倡议写上

    Connection connection = DriverManager.getConnection(url, user, password);

    System.out.println("形式 5" + connection);
}

ResultSet[后果集]

根本介绍

  1. 示意数据库后果集的数据表, 通常通过执行查询数据库的语句生成
  2. ResultSet 对象放弃一个光标指向其以后的数据行。最后,光标位于第一行之前
  3. next 办法将光标挪动到下一行,并且因为在 ResultSet 对象中没有更多行时返回 false,因而能够在 while 循环中应用循环来遍历后果集

利用实例

package com.hspedu.jdbc.resultset_;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * 演示 select 语句返回 ResultSet , 并取出后果
 */
@SuppressWarnings({"all"})
public class ResultSet_ {public static void main(String[] args) throws Exception {

        // 通过 Properties 对象获取配置文件的信息


        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        // 获取相干的值
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");

        //1. 注册驱动
        Class.forName(driver);// 倡议写上

        //2. 失去连贯
        Connection connection = DriverManager.getConnection(url, user, password);

        //3. 失去 Statement
        Statement statement = connection.createStatement();
        //4. 组织 SqL
        String sql = "select id, name , sex, borndate from actor";
        // 执行给定的 SQL 语句,该语句返回单个 ResultSet 对象
        /*
        +----+-----------+-----+---------------------+
        | id | name      | sex | borndate            |
        +----+-----------+-----+---------------------+-------+
        |  4 | 刘德华    | 男  | 1970-12-12 00:00:00 |
        |  5 | jack      | 男  | 1990-11-11 00:00:00 |
        +----+-----------+-----+---------------------+-------+
         */
        /*
            浏览 debug 代码 resultSet 对象的构造


         */
        ResultSet resultSet = statement.executeQuery(sql);
        // 初始时相似与指向表头
        //5. 应用 while 取出数据
        while (resultSet.next()) { // 让光标向后挪动,如果没有更多行,则返回 false
            int id  = resultSet.getInt(1); // 获取该行的第 1 列
            //int id1 = resultSet.getInt("id"); 通过列名来获取值, 举荐
            String name = resultSet.getString(2);// 获取该行的第 2 列
            String sex = resultSet.getString(3);
            Date date = resultSet.getDate(4);

            System.out.println(id + "\t" + name + "\t" + sex + "\t" + date);
        }

        //6. 敞开连贯
        resultSet.close();
        statement.close();
        connection.close();}
}

Statement

根本介绍

  1. Statement 对象用于执行动态 SQL 语句并返回其生成的后果的对象
  2. 在连贯建设后, 须要对数据库进行拜访,执行命名或是 SQL 语句,能够通过

    • Statement[存在 SQL 注入]
    • PreparedStatement[预处理]
    • CallableStatement[存储过程]
  3. Statement 对象执行 SQL 语句, 存在SQL 注入危险

  4. SQL 注入是利用某些零碎没有对用户输出的数据进行充沛的查看,而在用户输出数据中注入非法的 SQL 语句段或命令, 歹意攻打数据库。
  5. 要防备 SQL 注入,只有用 PreparedStatement(从 Statement 扩大而来)取代 Statement 就能够了。
package com.hspedu.jdbc.statement_;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;

/**
 * 演示 statement 的注入问题
 */
@SuppressWarnings({"all"})
public class Statement_ {public static void main(String[] args) throws Exception {Scanner scanner = new Scanner(System.in);

        // 让用户输出管理员名和明码
        System.out.print("请输出管理员的名字:");  //next(): 当接管到 空格或者 ' 就是示意完结
        String admin_name = scanner.nextLine(); // 老师阐明,如果心愿看到 SQL 注入,这里须要用 nextLine 直到回车才完结
        System.out.print("请输出管理员的明码:");
        String admin_pwd = scanner.nextLine();

        // 通过 Properties 对象获取配置文件的信息


        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        // 获取相干的值
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");

        //1. 注册驱动
        Class.forName(driver);// 倡议写上

        //2. 失去连贯
        Connection connection = DriverManager.getConnection(url, user, password);

        //3. 失去 Statement
        Statement statement = connection.createStatement();
        //4. 组织 SqL
        String sql = "select name , pwd  from admin where name ='"
                + admin_name + "'and pwd ='" + admin_pwd + "'";
        ResultSet resultSet = statement.executeQuery(sql);
        if (resultSet.next()) { // 如果查问到一条记录,则阐明该治理存在
            System.out.println("祝贺,登录胜利");
        } else {System.out.println("对不起,登录失败");
        }

        // 敞开连贯
        resultSet.close();
        statement.close();
        connection.close();}
}

PreparedStatement

根本介绍

String sql ="SELECT COUNT(*) FROM admin WHERE username =? AND PASSWORD=?";
  1. PreparedStatement 执行的 SQL 语句中的参数用问号 (?) 来示意,调用
    PreparedStatement 对象的 setXxx() 办法来设置这些参数. setXxx()办法有两个参数,第一个参数是要设置的 SQL 语句中的参数的索引(从 1 开始),第二个是设置的 SQL 语句中的参数的值
  2. 调用 executeQuery0),返回 ResultSet 对象
  3. 调用 executeUpdate(): 执行更新,包含增、删、批改

预处理益处

  1. 不再应用 + 拼接 sql 语句,缩小语法错误
  2. 无效的解决了 sql 注入问题!
  3. 大大减少了编译次数, 效率较高

利用案例

package com.hspedu.jdbc.preparedstatement_;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;

/**
 * 演示 PreparedStatement 应用
 */
@SuppressWarnings({"all"})
public class PreparedStatement_ {public static void main(String[] args) throws Exception {

        // 看 PreparedStatement 类图

        Scanner scanner = new Scanner(System.in);

        // 让用户输出管理员名和明码
        System.out.print("请输出管理员的名字:");  //next(): 当接管到 空格或者 ' 就是示意完结
        String admin_name = scanner.nextLine(); // 老师阐明,如果心愿看到 SQL 注入,这里须要用 nextLine
        System.out.print("请输出管理员的明码:");
        String admin_pwd = scanner.nextLine();

        // 通过 Properties 对象获取配置文件的信息

        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        // 获取相干的值
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");

        //1. 注册驱动
        Class.forName(driver);// 倡议写上

        //2. 失去连贯
        Connection connection = DriverManager.getConnection(url, user, password);

        //3. 失去 PreparedStatement
        //3.1 组织 SqL , Sql 语句的 ? 就相当于占位符
        String sql = "select name , pwd  from admin where name =? and pwd = ?";
        //3.2 preparedStatement 对象实现了 PreparedStatement 接口的实现类的对象
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //3.3 给 ? 赋值
        preparedStatement.setString(1, admin_name);
        preparedStatement.setString(2, admin_pwd);

        //4. 执行 select 语句应用  executeQuery
        //   如果执行的是 dml(update, insert ,delete) executeUpdate()
        //   这里执行 executeQuery , 不要再写 sql

        ResultSet resultSet = preparedStatement.executeQuery(sql);
        if (resultSet.next()) { // 如果查问到一条记录,则阐明该治理存在
            System.out.println("祝贺,登录胜利");
        } else {System.out.println("对不起,登录失败");
        }

        // 敞开连贯
        resultSet.close();
        preparedStatement.close();
        connection.close();}
}

操作 DML 语句

package com.hspedu.jdbc.preparedstatement_;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import java.util.Scanner;

/**
 * 演示 PreparedStatement 应用 dml 语句
 */
@SuppressWarnings({"all"})
public class PreparedStatementDML_ {public static void main(String[] args) throws Exception {

        // 看 PreparedStatement 类图

        Scanner scanner = new Scanner(System.in);

        // 让用户输出管理员名和明码
        System.out.print("请输删除管理员的名字:");  //next(): 当接管到 空格或者 ' 就是示意完结
        String admin_name = scanner.nextLine(); // 老师阐明,如果心愿看到 SQL 注入,这里须要用 nextLine
//        System.out.print("请输出管理员的新密码:");
//        String admin_pwd = scanner.nextLine();

        // 通过 Properties 对象获取配置文件的信息

        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        // 获取相干的值
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");

        //1. 注册驱动
        Class.forName(driver);// 倡议写上

        //2. 失去连贯
        Connection connection = DriverManager.getConnection(url, user, password);

        //3. 失去 PreparedStatement
        //3.1 组织 SqL , Sql 语句的 ? 就相当于占位符
        // 增加记录
        //String sql = "insert into admin values(?, ?)";
        //String sql = "update admin set pwd = ? where name = ?";
        String sql = "delete from  admin where name = ?";
        //3.2 preparedStatement 对象实现了 PreparedStatement 接口的实现类的对象
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //3.3 给 ? 赋值
        preparedStatement.setString(1, admin_name);

        //preparedStatement.setString(2, admin_name);

        //4. 执行 dml 语句应用  executeUpdate
        int rows = preparedStatement.executeUpdate();
        System.out.println(rows > 0 ? "执行胜利" : "执行失败");
        // 敞开连贯
        preparedStatement.close();
        connection.close();}
}

JDBC 的相干 API 小结

封装 JDBCUtils

阐明

在 jdbc 操作中,获取连贯和开释资源是常常应用到, 能够将其封装 DBC 连贯的工真类 JDBCUtils。

代码实现

package com.hspedu.jdbc.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * 这是一个工具类,实现 mysql 的连贯和敞开资源
 */
public class JDBCUtils {// 定义相干的属性(4 个), 因为只须要一份,因而,咱们做成 static
    private static String user; // 用户名
    private static String password; // 明码
    private static String url; //url
    private static String driver; // 驱动名

    // 在 static 代码块去初始化
    static {

        try {Properties properties = new Properties();
            properties.load(new FileInputStream("src\\mysql.properties"));
            // 读取相干的属性值
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            url = properties.getProperty("url");
            driver = properties.getProperty("driver");
        } catch (IOException e) {
            // 在理论开发中,咱们能够这样解决
            //1. 将编译异样转成 运行异样
            //2. 调用者,能够抉择捕捉该异样,也能够抉择默认解决该异样,比拟不便.
            throw new RuntimeException(e);

        }
    }

    // 连贯数据库, 返回 Connection
    public static Connection getConnection() {

        try {return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            //1. 将编译异样转成 运行异样
            //2. 调用者,能够抉择捕捉该异样,也能够抉择默认解决该异样,比拟不便.
            throw new RuntimeException(e);
        }
    }

    // 敞开相干资源
    /*
        1. ResultSet 后果集
        2. Statement 或者 PreparedStatement
        3. Connection
        4. 如果须要敞开资源,就传入对象,否则传入 null
     */
    public static void close(ResultSet set, Statement statement, Connection connection) {

        // 判断是否为 null
        try {if (set != null) {set.close();
            }
            if (statement != null) {statement.close();
            }
            if (connection != null) {connection.close();
            }
        } catch (SQLException e) {
            // 将编译异样转成运行异样抛出
            throw new RuntimeException(e);
        }
    }
}

测试

package com.hspedu.jdbc.utils;

import org.junit.jupiter.api.Test;

import java.sql.*;

/**
 * 该类演示如何应用 JDBCUtils 工具类,实现 dml 和 select
 */
public class JDBCUtils_Use {


    @Test
    public void testSelect() {
        //1. 失去连贯
        Connection connection = null;
        //2. 组织一个 sql
        String sql = "select * from actor where id = ?";
        PreparedStatement preparedStatement = null;
        ResultSet set = null;
        //3. 创立 PreparedStatement 对象
        try {connection = JDBCUtils.getConnection();
            System.out.println(connection.getClass()); //com.mysql.jdbc.JDBC4Connection
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 5);// 给? 号赋值
            // 执行, 失去后果集
            set = preparedStatement.executeQuery();
            // 遍历该后果集
            while (set.next()) {int id = set.getInt("id");
                String name = set.getString("name");
                String sex = set.getString("sex");
                Date borndate = set.getDate("borndate");
                String phone = set.getString("phone");
                System.out.println(id + "\t" + name + "\t" + sex + "\t" + borndate + "\t" + phone);
            }
        } catch (SQLException e) {e.printStackTrace();
        } finally {
            // 敞开资源
            JDBCUtils.close(set, preparedStatement, connection);
        }
    }

    @Test
    public void testDML() {//insert , update, delete

        //1. 失去连贯
        Connection connection = null;
        //2. 组织一个 sql
        String sql = "update actor set name = ? where id = ?";
        // 测试 delete 和 insert , 本人玩.
        PreparedStatement preparedStatement = null;
        //3. 创立 PreparedStatement 对象
        try {connection = JDBCUtils.getConnection();

            preparedStatement = connection.prepareStatement(sql);
            // 给占位符赋值
            preparedStatement.setString(1, "周星驰");
            preparedStatement.setInt(2, 4);
            // 执行
            preparedStatement.executeUpdate();} catch (SQLException e) {e.printStackTrace(); // 打印出错信息
        } finally {
            // 敞开资源
            JDBCUtils.close(null, preparedStatement, connection);
        }
    }
}

事务

根本介绍

  1. JDBC 程序中当一个 Connection 对象创立时,默认状况下是主动提交事务: 每次执行一个 SQL 语句时,如果执行胜利,就会向数据库主动提交,而不能回滚。
  2. JDBC 程序中为了让多个 SQL 语句作为一个整体执行,须要应用事务
  3. 调用 Connection 的 setAutoCommit(false)能够勾销主动提交事务
  4. 在所有的 SQL 语句都胜利执行后,调用 Connection 的 commit(); 办法提交事务
  5. 在其中某个操作失败或出现异常时,调用 Connection 的 rollback(); 办法回滚事务

利用实例

package com.hspedu.jdbc.transaction_;

import com.hspedu.jdbc.utils.JDBCUtils;
import org.junit.jupiter.api.Test;

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

/**
 * 演示 jdbc 中如何应用事务
 */
public class Transaction_ {

    // 没有应用事务.
    @Test
    public void noTransaction() {

        // 操作转账的业务
        //1. 失去连贯
        Connection connection = null;
        //2. 组织一个 sql
        String sql = "update account set balance = balance - 100 where id = 1";
        String sql2 = "update account set balance = balance + 100 where id = 2";
        PreparedStatement preparedStatement = null;
        //3. 创立 PreparedStatement 对象
        try {connection = JDBCUtils.getConnection(); // 在默认状况下,connection 是默认主动提交
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.executeUpdate(); // 执行第 1 条 sql

            int i = 1 / 0; // 抛出异样
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate(); // 执行第 3 条 sql} catch (SQLException e) {e.printStackTrace();
        } finally {
            // 敞开资源
            JDBCUtils.close(null, preparedStatement, connection);
        }
    }

    // 事务来解决
    @Test
    public void useTransaction() {

        // 操作转账的业务
        //1. 失去连贯
        Connection connection = null;
        //2. 组织一个 sql
        String sql = "update account set balance = balance - 100 where id = 1";
        String sql2 = "update account set balance = balance + 100 where id = 2";
        PreparedStatement preparedStatement = null;
        //3. 创立 PreparedStatement 对象
        try {connection = JDBCUtils.getConnection(); // 在默认状况下,connection 是默认主动提交
            // 将 connection 设置为不主动提交
            connection.setAutoCommit(false); // 相当于开启了事务
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.executeUpdate(); // 执行第 1 条 sql

            int i = 1 / 0; // 抛出异样
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate(); // 执行第 3 条 sql

            // 这里提交事务
            connection.commit();} catch (SQLException e) {
            // 这里咱们能够进行回滚,即撤销执行的 SQL
            // 默认回滚到事务开始的状态.
            System.out.println("执行产生了异样,撤销执行的 sql");
            try {connection.rollback();
            } catch (SQLException throwables) {throwables.printStackTrace();
            }
            e.printStackTrace();} finally {
            // 敞开资源
            JDBCUtils.close(null, preparedStatement, connection);
        }
    }
}

批处理

根本介绍

  1. 当须要成批插入或者更新记录时。能够采纳 Java 的批量更新机制,这一机制容许多条语句一次性提交给数据库批量解决。通常状况下比独自提交解决更有效率。
  2. JDBC 的批量解决语句包含上面办法:

    • addBatch(): 增加须要批量解决的 SQL 语句或参数
    • executeBatch(): 执行批量解决语句;
    • clearBatch(): 清空批处理包的语句
  3. JDBC 连贯 MySQL 时,如果要应用批处理性能,请在 url 中加参数?rewriteBatchedStatements = true
  4. 批处理往往和 PreparedStatement 一起搭配应用,能够既缩小编译次数,又减小运行次数,效率大大提高。
package com.hspedu.jdbc.batch_;

import com.hspedu.jdbc.utils.JDBCUtils;
import org.junit.jupiter.api.Test;

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

/**
 * 演示 java 的批处理
 */
public class Batch_ {

    // 传统办法,增加 5000 条数据到 admin2

    @Test
    public void noBatch() throws Exception {Connection connection = JDBCUtils.getConnection();
        String sql = "insert into admin2 values(null, ?, ?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        System.out.println("开始执行");
        long start = System.currentTimeMillis();// 开始工夫
        for (int i = 0; i < 5000; i++) {// 5000 执行
            preparedStatement.setString(1, "jack" + i);
            preparedStatement.setString(2, "666");
            preparedStatement.executeUpdate();}
        long end = System.currentTimeMillis();
        System.out.println("传统的形式 耗时 =" + (end - start));// 传统的形式 耗时 =10702
        // 敞开连贯
        JDBCUtils.close(null, preparedStatement, connection);
    }

    // 应用批量形式增加数据
    @Test
    public void batch() throws Exception {Connection connection = JDBCUtils.getConnection();
        String sql = "insert into admin2 values(null, ?, ?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        System.out.println("开始执行");
        long start = System.currentTimeMillis();// 开始工夫
        for (int i = 0; i < 5000; i++) {//5000 执行
            preparedStatement.setString(1, "jack" + i);
            preparedStatement.setString(2, "666");
            // 将 sql 语句退出到批处理包中 -> 看源码
            /*
            //1. // 第一就创立 ArrayList - elementData => Object[]
            //2. elementData => Object[] 就会寄存咱们预处理的 sql 语句
            //3. 当 elementData 满后, 就依照 1.5 扩容
            //4. 当增加到指定的值后,就 executeBatch
            //5. 批量解决会缩小咱们发送 sql 语句的网络开销,而且缩小编译次数,因而效率进步
            public void addBatch() throws SQLException {synchronized(this.checkClosed().getConnectionMutex()) {if (this.batchedArgs == null) {this.batchedArgs = new ArrayList();
                    }

                    for(int i = 0; i < this.parameterValues.length; ++i) {this.checkAllParametersSet(this.parameterValues[i], this.parameterStreams[i], i);
                    }

                    this.batchedArgs.add(new PreparedStatement.BatchParams(this.parameterValues, this.parameterStreams, this.isStream, this.streamLengths, this.isNull));
                }
            }

             */
            preparedStatement.addBatch();
            // 当有 1000 条记录时,在批量执行
            if((i + 1) % 1000 == 0) {// 满 1000 条 sql
                preparedStatement.executeBatch();
                // 清空一把
                preparedStatement.clearBatch();}
        }
        long end = System.currentTimeMillis();
        System.out.println("批量形式 耗时 =" + (end - start));// 批量形式 耗时 =108
        // 敞开连贯
        JDBCUtils.close(null, preparedStatement, connection);
    }
}

数据库连接池

5k 次连贯数据库问题

package com.hspedu.jdbc.datasource;

import com.hspedu.jdbc.utils.JDBCUtils;
import org.junit.jupiter.api.Test;

import java.sql.Connection;

public class ConQuestion {

    // 代码 连贯 mysql 5000 次
    @Test
    public void testCon() {

        // 看看连贯 - 敞开 connection 会耗用多久
        long start = System.currentTimeMillis();
        System.out.println("开始连贯.....");
        for (int i = 0; i < 5000; i++) {
            // 应用传统的 jdbc 形式,失去连贯
            Connection connection = JDBCUtils.getConnection();
            // 做一些工作,比方失去 PreparedStatement,发送 sql
            //..........
            // 敞开
            JDBCUtils.close(null, null, connection);

        }
        long end = System.currentTimeMillis();
        System.out.println("传统形式 5000 次 耗时 =" + (end - start));// 传统形式 5000 次 耗时 =7099
    }
}

传统获取 Connection 问题剖析

  1. 传统的 JDBC 数据库连贯应用 DriverManager 来获取,每次向数据库建设连贯的时候都要将 Connection 加载到内存中,再验证 IP 地址,用户名和明码(0.05s~1s 工夫)。须要数据库连贯的时候, 就向数据库要求一个, 频繁的进行数据库连贯操作将占用很多的系统资源,容易造成服务器解体。
  2. 每一次数据库连贯,应用完后都得断开, 如果程序出现异常而未能敞开,将导致 数据库内存透露,最终将导致重启数据库。
  3. 传统获取连贯的形式, 不能管制创立的连贯数量,如连贯过多,也可能导致 内存透露,MySQL 解体。
  4. 解决传统开发中的数据库连贯问题, 能够采纳 数据库连接池技术
    (connection pool)。

数据库连接池品种

  1. JDBC 的数据库连接池应用 javax.sqI.DataSource 来示意,DataSource 只是一个接口, 该接口通常由第三方提供实现[提供.jar]
  2. C3P0数据库连接池, 速度绝对较慢,稳定性不错(hibernate, spring)
  3. DBCP 数据库连接池, 速度绝对 c3p0 较快, 但不稳固
  4. Proxool 数据库连接池,有监控连接池状态的性能,稳定性较 c3p0 差一点
  5. BoneCP 数据库连接池, 速度快
  6. Druid(德鲁伊)是阿里提供的数据库连接池,集 DBCP、C3P0、Proxool 长处于一身的数据库连接池

C3P0 利用实例

两种连贯形式:

package com.hspedu.jdbc.datasource;


import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 演示 c3p0 的应用
 */
public class C3P0_ {

    // 形式 1:相干参数,在程序中指定 user, url , password 等
    @Test
    public void testC3P0_01() throws Exception {

        //1. 创立一个数据源对象
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        //2. 通过配置文件 mysql.properties 获取相干连贯的信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        // 读取相干的属性值
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");

        // 给数据源 comboPooledDataSource 设置相干的参数
        // 留神:连贯治理是由 comboPooledDataSource 来治理
        comboPooledDataSource.setDriverClass(driver);
        comboPooledDataSource.setJdbcUrl(url);
        comboPooledDataSource.setUser(user);
        comboPooledDataSource.setPassword(password);

        // 设置初始化连接数
        comboPooledDataSource.setInitialPoolSize(10);
        // 最大连接数
        comboPooledDataSource.setMaxPoolSize(50);
        // 测试连接池的效率, 测试对 mysql 5000 次操作
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {Connection connection = comboPooledDataSource.getConnection(); // 这个办法就是从 DataSource 接口实现的
            //System.out.println("连贯 OK");
            connection.close();}
        long end = System.currentTimeMillis();
        //c3p0 5000 连贯 mysql 耗时 =391
        System.out.println("c3p0 5000 连贯 mysql 耗时 =" + (end - start));

    }

    // 第二种形式 应用配置文件模板来实现

    //1. 将 c3p0 提供的 c3p0.config.xml 拷贝到 src 目录下(配置文件名字不能乱写,要依照规定)//2. 该文件指定了连贯数据库和连接池的相干参数
    @Test
    public void testC3P0_02() throws SQLException {ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("hsp_edu");

        // 测试 5000 次连贯 mysql
        long start = System.currentTimeMillis();
        System.out.println("开始执行....");
        for (int i = 0; i < 500000; i++) {Connection connection = comboPooledDataSource.getConnection();
            //System.out.println("连贯 OK~");
            connection.close();}
        long end = System.currentTimeMillis();
        //c3p0 的第二种形式 耗时 =413
        System.out.println("c3p0 的第二种形式(500000) 耗时 =" + (end - start));//1917
    }
}
<c3p0-config>
    <!-- 数据源名称代表连接池 -->
  <named-config name="hsp_edu">
<!-- 驱动类 -->
  <property name="driverClass">com.mysql.jdbc.Driver</property>
  <!-- url-->
   <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/hsp_db02</property>
  <!-- 用户名 -->
      <property name="user">root</property>
      <!-- 明码 -->
   <property name="password">hsp</property>
   <!-- 每次增长的连接数 -->
    <property name="acquireIncrement">5</property>
    <!-- 初始的连接数 -->
    <property name="initialPoolSize">10</property>
    <!-- 最小连接数 -->
    <property name="minPoolSize">5</property>
   <!-- 最大连接数 -->
    <property name="maxPoolSize">50</property>

   <!-- 可连贯的最多的命令对象数 -->
    <property name="maxStatements">5</property> 
    
    <!-- 每个连贯对象可连贯的最多的命令对象数 -->
    <property name="maxStatementsPerConnection">2</property>
  </named-config>
</c3p0-config>

Druid(德鲁伊)利用实例

#key=value
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/hsp_db02?rewriteBatchedStatements=true
username=root
password=hsp
#initial connection Size
initialSize=10
#min idle connecton size
minIdle=5
#max active connection size
maxActive=50
#max wait time (5000 mil seconds)
maxWait=5000
package com.hspedu.jdbc.datasource;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.jupiter.api.Test;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.util.Properties;

/**
 * 测试 druid 的应用
 */
public class Druid_ {

    @Test
    public void testDruid() throws Exception {
        //1. 退出 Druid jar 包
        //2. 退出 配置文件 druid.properties , 将该文件拷贝我的项目的 src 目录
        //3. 创立 Properties 对象, 读取配置文件
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\druid.properties"));

        //4. 创立一个指定参数的数据库连接池, Druid 连接池
        DataSource dataSource =
                DruidDataSourceFactory.createDataSource(properties);

        long start = System.currentTimeMillis();
        for (int i = 0; i < 500000; i++) {Connection connection = dataSource.getConnection();
            System.out.println(connection.getClass());
            //System.out.println("连贯胜利!");
            connection.close();}
        long end = System.currentTimeMillis();
        //druid 连接池 操作 5000 耗时 =412
        System.out.println("druid 连接池 操作 500000 耗时 =" + (end - start));//539
    }
}

将 JDBCUtils 工具类改成 Druid(德鲁伊)实现

通过德鲁伊数据库连接池获取连贯对象

package com.hspedu.jdbc.datasource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 基于 druid 数据库连接池的工具类
 */
public class JDBCUtilsByDruid {

    private static DataSource ds;

    // 在动态代码块实现 ds 初始化
    static {Properties properties = new Properties();
        try {properties.load(new FileInputStream("src\\druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {e.printStackTrace();
        }

    }

    // 编写 getConnection 办法
    public static Connection getConnection() throws SQLException {return ds.getConnection();
    }

    // 敞开连贯, 老师再次强调:在数据库连接池技术中,close 不是真的断掉连贯
    // 而是把应用的 Connection 对象放回连接池
    public static void close(ResultSet resultSet, Statement statement, Connection connection) {

        try {if (resultSet != null) {resultSet.close();
            }
            if (statement != null) {statement.close();
            }
            if (connection != null) {
                // 特地留神:这里 close 办法与元生的 close 办法不一样,这里仅是放回连接池。connection.close();}
        } catch (SQLException e) {throw new RuntimeException(e);
        }
    }
}
package com.hspedu.jdbc.datasource;


import org.junit.jupiter.api.Test;

import java.sql.*;
import java.util.ArrayList;

@SuppressWarnings({"all"})
public class JDBCUtilsByDruid_USE {

    @Test
    public void testSelect() {System.out.println("应用 druid 形式实现");
        //1. 失去连贯
        Connection connection = null;
        //2. 组织一个 sql
        String sql = "select * from actor where id >= ?";
        PreparedStatement preparedStatement = null;
        ResultSet set = null;
        //3. 创立 PreparedStatement 对象
        try {connection = JDBCUtilsByDruid.getConnection();
            System.out.println(connection.getClass());// 运行类型 com.alibaba.druid.pool.DruidPooledConnection
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 1);// 给? 号赋值
            // 执行, 失去后果集
            set = preparedStatement.executeQuery();

            // 遍历该后果集
            while (set.next()) {int id = set.getInt("id");
                String name = set.getString("name");//getName()
                String sex = set.getString("sex");//getSex()
                Date borndate = set.getDate("borndate");
                String phone = set.getString("phone");
                System.out.println(id + "\t" + name + "\t" + sex + "\t" + borndate + "\t" + phone);
            }
        } catch (SQLException e) {e.printStackTrace();
        } finally {
            // 敞开资源
            JDBCUtilsByDruid.close(set, preparedStatement, connection);
        }
    }
}

Apache—DBUtils

先剖析一个问题

  1. 敞开 connection 后,resultSet 后果集无奈应用
  2. resultSet 不利于数据的治理
  3. 示意图

这种 java 类叫做 JavaBean,PoJo 或者 Domain。

自定义办法解决

package com.hspedu.jdbc.datasource;

import java.util.Date;

/**
 * Actor 对象和 actor 表的记录对应
 */
public class Actor { //Javabean, POJO, Domain 对象

    private Integer id;
    private String name;
    private String sex;
    private Date borndate;
    private String phone;

    public Actor() { // 肯定要给一个无参结构器[反射须要]
    }

    public Actor(Integer id, String name, String sex, Date borndate, String phone) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.borndate = borndate;
        this.phone = phone;
    }

    public Integer getId() {return id;}

    public void setId(Integer id) {this.id = id;}

    public String getName() {return name;}

    public void setName(String name) {this.name = name;}

    public String getSex() {return sex;}

    public void setSex(String sex) {this.sex = sex;}

    public Date getBorndate() {return borndate;}

    public void setBorndate(Date borndate) {this.borndate = borndate;}

    public String getPhone() {return phone;}

    public void setPhone(String phone) {this.phone = phone;}

    @Override
    public String toString() {
        return "\nActor{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", borndate=" + borndate +
                ", phone='" + phone + '\'' +
                '}';
    }
}
    // 应用老师的土办法来解决 ResultSet = 封装 => Arraylist
    @Test
    public ArrayList<Actor> testSelectToArrayList() {System.out.println("应用 druid 形式实现");
        //1. 失去连贯
        Connection connection = null;
        //2. 组织一个 sql
        String sql = "select * from actor where id >= ?";
        PreparedStatement preparedStatement = null;
        ResultSet set = null;
        ArrayList<Actor> list = new ArrayList<>();// 创立 ArrayList 对象, 寄存 actor 对象
        //3. 创立 PreparedStatement 对象
        try {connection = JDBCUtilsByDruid.getConnection();
            System.out.println(connection.getClass());// 运行类型 com.alibaba.druid.pool.DruidPooledConnection
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 1);// 给? 号赋值
            // 执行, 失去后果集
            set = preparedStatement.executeQuery();

            // 遍历该后果集
            while (set.next()) {int id = set.getInt("id");
                String name = set.getString("name");//getName()
                String sex = set.getString("sex");//getSex()
                Date borndate = set.getDate("borndate");
                String phone = set.getString("phone");
                // 把失去的 resultset 的记录,封装到 Actor 对象,放入到 list 汇合
                list.add(new Actor(id, name, sex, borndate, phone));
            }

            System.out.println("list 汇合数据 =" + list);
            for(Actor actor : list) {System.out.println("id=" + actor.getId() + "\t" + actor.getName());
            }

        } catch (SQLException e) {e.printStackTrace();
        } finally {
            // 敞开资源
            JDBCUtilsByDruid.close(set, preparedStatement, connection);
        }
        // 因为 ArrayList 和 connection 没有任何关联,所以该汇合能够复用.
        return  list;
    }

根本介绍

commons-dbutils 是 Apache 组织提供的一个开源 JDBC 工具类库,它是对 JDBC 的封装,应用 dbutils 能极大简化 jdbc 编码的工作量。

  1. DbUtils 类:
  2. QueryRunner 类: 该类封装了 SQL 的执行,是线程平安的。能够实现增、删、改、查、批处理。
  3. 应用 QueryRunner 类实现查问。
  4. ResultSetHandler 接口:该接口用于解决 java.sql.ResultSet,将数据按要求转换为另一种模式。

    • ArrayHandler: 把后果集中的第一行数据转成对象数组。
    • ArrayListHandler: 把后果集中的每一行数据都转成一个数组,再寄存到 List 中。
    • BeanHandler: 将后果集中的第一行数据封装到一个对应的 JavaBean 实例中。
    • BeanListHandler: 将后果集中的每一行数据都封装到一个对应的 JavaBean 实例中,寄存到 List 里。
    • ColumnListHandler: 将后果集中某一列的数据寄存到 List 中。
    • KeyedHandler(name): 将后果集中的每行数据都封装到 Map 里,再把这些 map 再存到一个 map 里,其 key 为指定的 key。
    • MapHandler: 将后果集中的第一行数据封装到一个 Map 里,key 是列名,value 就是对应的值。
    • MapListHandler: 将后果集中的每一行数据都封装到一个 Map 里,而后再寄存到 List。

利用实例

应用 DBUtils+ 数据连接池 (德鲁伊) 形式,实现对表 actor 的 crud

package com.hspedu.jdbc.datasource;


import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.jupiter.api.Test;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings({"all"})
public class DBUtils_USE {

    // 应用 apache-DBUtils 工具类 + druid 实现对表的 crud 操作
    @Test
    public void testQueryMany() throws SQLException { // 返回后果是多行的状况

        //1. 失去 连贯 (druid)
        Connection connection = JDBCUtilsByDruid.getConnection();
        //2. 应用 DBUtils 类和接口 , 先引入 DBUtils 相干的 jar , 退出到本 Project
        //3. 创立 QueryRunner
        QueryRunner queryRunner = new QueryRunner();
        //4. 就能够执行相干的办法,返回 ArrayList 后果集
        //String sql = "select * from actor where id >= ?";
        //   留神: sql 语句也能够查问局部列
        String sql = "select id, name from actor where id >= ?";
        //(1) query 办法就是执行 sql 语句,失去 resultset --- 封装到 --> ArrayList 汇合中
        //(2) 返回汇合
        //(3) connection: 连贯
        //(4) sql : 执行的 sql 语句
        //(5) new BeanListHandler<>(Actor.class): 在将 resultset -> Actor 对象 -> 封装到 ArrayList
        //    底层应用反射机制 去获取 Actor 类的属性,而后进行封装
        //(6) 1 就是给 sql 语句中的? 赋值,能够有多个值,因为是可变参数 Object... params
        //(7) 底层失去的 resultset , 会在 query 敞开, 并且敞开 PreparedStatment,所以只须要传入 connection 就能够。/**
         * 剖析 queryRunner.query 办法:
         * public <T> T query(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException {
         *         PreparedStatement stmt = null;// 定义 PreparedStatement
         *         ResultSet rs = null;// 接管返回的 ResultSet
         *         Object result = null;// 返回 ArrayList
         *
         *         try {*             stmt = this.prepareStatement(conn, sql);// 创立 PreparedStatement
         *             this.fillStatement(stmt, params);// 对 sql 进行 ? 赋值
         *             rs = this.wrap(stmt.executeQuery());// 执行 sql, 返回 resultset
         *             result = rsh.handle(rs);// 返回的 resultset --> arrayList[result] [应用到反射,对传入 class 对象解决]
         *         } catch (SQLException var33) {*             this.rethrow(var33, sql, params);
         *         } finally {
         *             try {*                 this.close(rs);// 敞开 resultset
         *             } finally {*                 this.close((Statement)stmt);// 敞开 preparedstatement 对象
         *             }
         *         }
         *
         *         return result;
         *     }
         */
        List<Actor> list =
                queryRunner.query(connection, sql, new BeanListHandler<>(Actor.class), 1);
        System.out.println("输入汇合的信息");
        for (Actor actor : list) {System.out.print(actor);
        }


        // 开释资源
        JDBCUtilsByDruid.close(null, null, connection);

    }

    // 演示 apache-dbutils + druid 实现 返回的后果是单行记录(单个对象)
    @Test
    public void testQuerySingle() throws SQLException {//1. 失去 连贯 (druid)
        Connection connection = JDBCUtilsByDruid.getConnection();
        //2. 应用 DBUtils 类和接口 , 先引入 DBUtils 相干的 jar , 退出到本 Project
        //3. 创立 QueryRunner
        QueryRunner queryRunner = new QueryRunner();
        //4. 就能够执行相干的办法,返回单个对象
        String sql = "select * from actor where id = ?";
        // 因为咱们返回的单行记录 <---> 单个对象 , 应用的 Hander 是 BeanHandler
        Actor actor = queryRunner.query(connection, sql, new BeanHandler<>(Actor.class), 10);
        System.out.println(actor);

        // 开释资源
        JDBCUtilsByDruid.close(null, null, connection);

    }

    // 演示 apache-dbutils + druid 实现查问后果是单行单列 - 返回的就是 object
    @Test
    public void testScalar() throws SQLException {//1. 失去 连贯 (druid)
        Connection connection = JDBCUtilsByDruid.getConnection();
        //2. 应用 DBUtils 类和接口 , 先引入 DBUtils 相干的 jar , 退出到本 Project
        //3. 创立 QueryRunner
        QueryRunner queryRunner = new QueryRunner();

        //4. 就能够执行相干的办法,返回单行单列 , 返回的就是 Object
        String sql = "select name from actor where id = ?";
        // 老师解读:因为返回的是一个对象, 应用的 handler 就是 ScalarHandler
        Object obj = queryRunner.query(connection, sql, new ScalarHandler(), 4);
        System.out.println(obj);

        // 开释资源
        JDBCUtilsByDruid.close(null, null, connection);
    }

    // 演示 apache-dbutils + druid 实现 dml (update, insert ,delete)
    @Test
    public void testDML() throws SQLException {//1. 失去 连贯 (druid)
        Connection connection = JDBCUtilsByDruid.getConnection();
        //2. 应用 DBUtils 类和接口 , 先引入 DBUtils 相干的 jar , 退出到本 Project
        //3. 创立 QueryRunner
        QueryRunner queryRunner = new QueryRunner();

        //4. 这里组织 sql 实现 update, insert delete
        //String sql = "update actor set name = ? where id = ?";
        //String sql = "insert into actor values(null, ?, ?, ?, ?)";
        String sql = "delete from actor where id = ?";

        //(1) 执行 dml 操作是 queryRunner.update()
        //(2) 返回的值是受影响的行数 (affected: 受影响)
        //int affectedRow = queryRunner.update(connection, sql, "林青霞", "女", "1966-10-10", "116");
        int affectedRow = queryRunner.update(connection, sql, 1000);
        System.out.println(affectedRow > 0 ? "执行胜利" : "执行没有影响到表");

        // 开释资源
        JDBCUtilsByDruid.close(null, null, connection);

    }
}

表 和 JavaBean 的类型映射关系

DAO 和增删改查通用办法 -BasicDao

先剖析一个问题

apache-dbutils+ Druid 简化了 JDBC 开发, 但还有有余:

  1. SQL 语句是固定,不能通过参数传入,通用性不好,须要进行改良,更不便执行增删改查
  2. 对于 select 操作,如果有返回值,返回类型不能固定,须要应用泛型
  3. 未来的表很多,业务需要简单, 不可能只靠一个 Java 类实现
  4. 引出 =》BasicDAO 画出示意图,看看在理论开发中,应该如何解决

根本阐明

  1. DAO : data access object 数据拜访对象
  2. 这样的通用类,称为 BasicDao,是专门和数据库交互的,即实现对数据库 (表) 的 crud 操作。
  3. 在 BaiscDao 的根底上,实现一张表对应一个 Dao,更好的实现性能,比方 Customer 表 -Customer.java 类(javabean)-CustomerDao.java

BasicDAO 利用实例

实现一个简略设计com.hspedu.dao_

  1. com.hspedu.dao _.utils // 工具类
  2. com.hspedu.dao_.domain // javabean
  3. com.hspedu.dao_.dao// 寄存 XxxDAO 和 BasicDAO_
  4. com.hspedu.dao_.test // 写测试类

com/hspedu/dao_/domain/Actor.java

package com.hspedu.dao_.domain;

import java.util.Date;

/**
 * Actor 对象和 actor 表的记录对应
 */
public class Actor { //Javabean, POJO, Domain 对象

    private Integer id;
    private String name;
    private String sex;
    private Date borndate;
    private String phone;

    public Actor() { // 肯定要给一个无参结构器[反射须要]
    }

    public Actor(Integer id, String name, String sex, Date borndate, String phone) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.borndate = borndate;
        this.phone = phone;
    }

    public Integer getId() {return id;}

    public void setId(Integer id) {this.id = id;}

    public String getName() {return name;}

    public void setName(String name) {this.name = name;}

    public String getSex() {return sex;}

    public void setSex(String sex) {this.sex = sex;}

    public Date getBorndate() {return borndate;}

    public void setBorndate(Date borndate) {this.borndate = borndate;}

    public String getPhone() {return phone;}

    public void setPhone(String phone) {this.phone = phone;}

    @Override
    public String toString() {
        return "\nActor{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", borndate=" + borndate +
                ", phone='" + phone + '\'' +
                '}';
    }
}

com/hspedu/dao_/utils/JDBCUtilsByDruid.java

package com.hspedu.dao_.domain;

import java.util.Date;

/**
 * Actor 对象和 actor 表的记录对应
 */
public class Actor { //Javabean, POJO, Domain 对象

    private Integer id;
    private String name;
    private String sex;
    private Date borndate;
    private String phone;

    public Actor() { // 肯定要给一个无参结构器[反射须要]
    }

    public Actor(Integer id, String name, String sex, Date borndate, String phone) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.borndate = borndate;
        this.phone = phone;
    }

    public Integer getId() {return id;}

    public void setId(Integer id) {this.id = id;}

    public String getName() {return name;}

    public void setName(String name) {this.name = name;}

    public String getSex() {return sex;}

    public void setSex(String sex) {this.sex = sex;}

    public Date getBorndate() {return borndate;}

    public void setBorndate(Date borndate) {this.borndate = borndate;}

    public String getPhone() {return phone;}

    public void setPhone(String phone) {this.phone = phone;}

    @Override
    public String toString() {
        return "\nActor{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", borndate=" + borndate +
                ", phone='" + phone + '\'' +
                '}';
    }
}

com/hspedu/dao_/dao/BasicDAO.java

package com.hspedu.dao_.dao;

import com.hspedu.dao_.utils.JDBCUtilsByDruid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * 开发 BasicDAO , 是其余 DAO 的父类
 */
public class BasicDAO<T> { // 泛型指定具体类型

    private QueryRunner qr =  new QueryRunner();

    // 开发通用的 dml 办法, 针对任意的表
    public int update(String sql, Object... parameters) {
        Connection connection = null;

        try {connection = JDBCUtilsByDruid.getConnection();
            int update = qr.update(connection, sql, parameters);
            return  update;
        } catch (SQLException e) {throw  new RuntimeException(e); // 将编译异样 -> 运行异样 , 抛出
        } finally {JDBCUtilsByDruid.close(null, null, connection);
        }
    }

    // 返回多个对象(即查问的后果是多行), 针对任意表

    /**
     *
     * @param sql sql 语句,能够有 ?
     * @param clazz 传入一个类的 Class 对象 比方 Actor.class
     * @param parameters 传入 ? 的具体的值,能够是多个
     * @return 依据 Actor.class 返回对应的 ArrayList 汇合
     */
    public List<T> queryMulti(String sql, Class<T> clazz, Object... parameters) {

        Connection connection = null;
        try {connection = JDBCUtilsByDruid.getConnection();
            return qr.query(connection, sql, new BeanListHandler<T>(clazz), parameters);

        } catch (SQLException e) {throw  new RuntimeException(e); // 将编译异样 -> 运行异样 , 抛出
        } finally {JDBCUtilsByDruid.close(null, null, connection);
        }

    }

    // 查问单行后果 的通用办法
    public T querySingle(String sql, Class<T> clazz, Object... parameters) {

        Connection connection = null;
        try {connection = JDBCUtilsByDruid.getConnection();
            return  qr.query(connection, sql, new BeanHandler<T>(clazz), parameters);

        } catch (SQLException e) {throw  new RuntimeException(e); // 将编译异样 -> 运行异样 , 抛出
        } finally {JDBCUtilsByDruid.close(null, null, connection);
        }
    }

    // 查问单行单列的办法, 即返回单值的办法

    public Object queryScalar(String sql, Object... parameters) {

        Connection connection = null;
        try {connection = JDBCUtilsByDruid.getConnection();
            return  qr.query(connection, sql, new ScalarHandler(), parameters);

        } catch (SQLException e) {throw  new RuntimeException(e); // 将编译异样 -> 运行异样 , 抛出
        } finally {JDBCUtilsByDruid.close(null, null, connection);
        }
    }
}

com/hspedu/dao_/dao/ActorDAO.java

package com.hspedu.dao_.dao;

import com.hspedu.dao_.domain.Actor;

public class ActorDAO extends BasicDAO<Actor> {
    //1. 就有 BasicDAO 的办法
    //2. 依据业务需要,能够编写特有的办法.
}

com/hspedu/dao_/test/TestDAO.java

package com.hspedu.dao_.test;

import com.hspedu.dao_.dao.ActorDAO;
import com.hspedu.dao_.domain.Actor;
import org.junit.jupiter.api.Test;

import java.util.List;

public class TestDAO {

    // 测试 ActorDAO 对 actor 表 crud 操作
    @Test
    public void testActorDAO() {ActorDAO actorDAO = new ActorDAO();
        //1. 查问
        List<Actor> actors = actorDAO.queryMulti("select * from actor where id >= ?", Actor.class, 1);
        System.out.println("=== 查问后果 ===");
        for (Actor actor : actors) {System.out.println(actor);
        }

        //2. 查问单行记录
        Actor actor = actorDAO.querySingle("select * from actor where id = ?", Actor.class, 6);
        System.out.println("==== 查问单行后果 ====");
        System.out.println(actor);

        //3. 查问单行单列
        Object o = actorDAO.queryScalar("select name from actor where id = ?", 6);
        System.out.println("==== 查问单行单列值 ===");
        System.out.println(o);

        //4. dml 操作  insert ,update, delete
        int update = actorDAO.update("insert into actor values(null, ?, ?, ?, ?)", "张无忌", "男", "2000-11-11", "999");

        System.out.println(update > 0 ? "执行胜利" : "执行没有影响表");
    }
}

正文完
 0