JDBC技术

第 1 章 JDBC概述

1.1 数据的持久化

1)持久化(persistence):把数据保存到可掉电式存储设备中以供之后使用。大多 数情况下,特别是企业级应用,数据持久化意味着将内存中的数据保存到硬盘上加以”固化” ,而持久化的实现过程大多通过各种关系数据库来完成。

2) 持久化的主要应用是将内存中的数据存储在关系型数据库中,当然也可以存储 在磁盘文件、XML数据文件中 。

1.2 Java中的数据存储技术

在Java中,数据库存取技术可分为如下几类:

JDBC直接访问数据库

JDO技术

第三方O/R工具,如Hibernate, mybatis 等

JDBC是java访问数据库的基石,JDO, Hibernate等只是更好 的封装了JDBC

1.3 JDBC介绍

1) JDBC(Java Database Connectivity)是一个独立于特定数据库管理系统、 通用的SQL数据库存取和操作的公共接口(一组API),定义了用来访问 数据库的标准Java类库,(java.sql,javax.sql)使用这个类库可以以一种 标准的方法、方便地访问数据库资源

2) JDBC为访问不同的数据库提供了一种统一的途径,为开发者屏蔽了一些 细节问题。

3) JDBC的目标是使Java程序员使用JDBC可以连接任何提供了JDBC驱动程序的数据库系统,这样就使得程序员无需对特定的数据库系统的特点有过多的了解,从而大大简化和加快了开发过程。

1.4 JDBC体系结构

JDBC接口(API)包括两个层次:

面向应用的API:Java API,抽象接口,供应用程序开发人员使用(连接数据库, 执行SQL语句,获得结果)。

面向数据库的API:Java Driver API,供开发商开发数据库驱动程序用。

jdbc API

1.5 JDBC程序访问数据库步骤

第 2 章 获取数据库连接

要素一:Driver接口实现类

1.Driver接口介绍

java.sql.Driver 接口是所有 JDBC 驱动程序需要实现的接口。这个接口是提 供给数据库厂商使用的,不同数据库厂商提供不同的实现。

在程序中不需要直接去访问实现了 Driver 接口的类,而是由驱动程序管理 器类(java.sql.DriverManager)去调用这些 Driver 实现

Oracle的驱动:oracle.jdbc.driver.OracleDriver

mysql的驱动: com.mysql.jdbc.Driver

2.加载与注册JDBC驱动

1)实现方式(1234)

@Test
    public void testConnection1() throws SQLException {
        //获取driver的实现类对象
        Driver driver = new com.mysql.jdbc.Driver();

        String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
        //jdbc:mysql:协议
        //localhost:ip地址
        //3306:默认mysql的端口号
        //test:要连接的数据库名称
        Properties info = new Properties();
        info.setProperty("user","root");
        info.setProperty("password","Zdy!230003#");
        //将用户名和密码封装在Properties()中

        Connection conn = driver.connect(url, info);
        System.out.println(conn);
    }

    //方式二:对方式一的迭代:在如下的程序中不出现第三方的api,是的程序具有更好的可移植性
    @Test
    public void testConnection2() throws Exception {
        //1.获取Driver实现类对象,使用反射
        Class<?> clazz = Class.forName("com.mysql.jdbc.Driver");
        Driver driver = (Driver) clazz.newInstance();

        //2.提供要连接的数据库
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";

        //3.提供连接需要的用户名和密码
        Properties info = new Properties();
        info.setProperty("user","root");
        info.setProperty("password","Zdy!230003#");

        //4.获取连接
        Connection conn = driver.connect(url, info);
        System.out.println(conn);

    }

    //方式三:使用DriverManager替换Driver
    @Test
    public void testConnection3() throws Exception {
        //1.提供另外三个连接的基本信息:
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
        String user = "root";
        String password = "Zdy!230003#";

        //2.获取Driver的实现类对象
        Class clazz = Class.forName("com.mysql.jdbc.Driver");
        Driver driver = (Driver) clazz.newInstance();

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

        //4.获取连接
        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);
    }

    //方式四:
    @Test
    public void testConnection4() throws Exception{
        //1.提供另外三个连接的基本信息:
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
        String user = "root";
        String password = "Zdy!230003#";

        //2.加载Driver
        Class.forName("com.mysql.jdbc.Driver");
        //相较于方式三,可以省略如下的操作
//        Driver driver = (Driver) clazz.newInstance();
//
//        //3.注册驱动
//        DriverManager.registerDriver(driver);
        //为什么可以省略上述操作?
        //在mysql的Driver实现类中,静态方法区实现了上述操作
        //4.获取连接
        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);
    }

2)实际生产环境中的实现方式

public Class ConnectionTest{
    //方式五:将数据库连接需要的4个基本信息声明在配置文件中,通过读取配置文件的方式,获取连接
    @Test
    public void getConnection5() throws Exception{
        //1.读取配置文件中的4个基本信息
        ClassLoader classLoader = ConnectionTest.class.getClassLoader();
        InputStream ras = classLoader.getResourceAsStream("jdbc.properties");
        Properties pros = new Properties();
        pros.load(ras);

        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        String url = pros.getProperty("url");

        //2.注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //为什么可以省略操作?
        //在mysql的Driver实现类中,静态方法区实现了上述操作
        
        //3.建立连接
        Connection connection = DriverManager.getConnection(url, user, password);

        System.out.println(connection);
    }
}

优点:

1.实现类数据与代码的分离。实现了解耦

2.如果需要修改配置文件信息,可以避免程序重新打包

3.建立连接

第 3 章 使用PreparedStatement实现CRUD操作

一、操作和访问数据库

1.数据库连接被用于向数据库服务器发送命令和 SQL 语句,在连接建立后,需要对数据库进行访问,执行 sql 语句

2.在 java.sql 包中有 3 个接口分别定义了对数据库的调用的不同方式:

Statement

PreparedStatement

CallableStatement

二、使用Statement操作数据库的弊端

如何避免SQL注入攻击?

只要用PreparedStatement(从Statement扩展而来)取代Statement

三、数据的增删改操作

1.数据的增加

public class PreparedStatementTest {

    //想customers表中添加一条记录
    @Test
    public void testInsert(){
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            ClassLoader classLoader = PreparedStatementTest.class.getClassLoader();
            InputStream ras = classLoader.getResourceAsStream("jdbc.properties");
            Properties pros = new Properties();
            pros.load(ras);

            String user = pros.getProperty("user");
            String password = pros.getProperty("password");
            String url = pros.getProperty("url");
            String driverClass = pros.getProperty("driverClass");

            //2.加载驱动
            Class.forName(driverClass);
            //3.获取连接
            connection = connection = DriverManager.getConnection(url, user, password);

            System.out.println(connection);

            //4.预编译sql语句
            String sql = "insert into customers(name,email,birth) values(?,?,?)";//?占位符
            ps = connection.prepareStatement(sql);

            //5.填充占位符
            ps.setString(1,"Mbappe");
            ps.setString(2,"Mbappe@qq.com");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date date = sdf.parse("1998-01-01");
            ps.setDate(3,new Date(date.getTime()));

            //6.执行操作
            ps.execute();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } finally{
            //7.资源的关闭
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }
}

2、通用的增删改操作

通常我们将数据库的连接和资源的关闭操作封装到JDBCUtils类中,以便直接调用

public class JDBCUtils {
    
    //获取数据库的连接
    public static Connection getConnection() throws Exception{

        InputStream ras = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
        Properties pros = new Properties();
        pros.load(ras);

        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        String url = pros.getProperty("url");
        String driverClass = pros.getProperty("driverClass");

        //2.加载驱动
        Class.forName(driverClass);
        //3.获取连接
        Connection connection = DriverManager.getConnection(url, user, password);

        return connection;
    }

    //关闭连接和Statement
    public static void closeResource(Connection conn, Statement ps){
        //7.资源的关闭
        try {
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

在实际操作中,我们可以将增删改封装到一个共同的方法中,通过设置可变形参,来对应传入不同操作下的占位符,占位符的个数与可变形参的长度相同

//通用的增删改操作
    public void update(String sql,Object ...args){//sql中占位符的个数与可变形参的长度相同
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            //1.获取数据库的连接
            connection = JDBCUtils.getConnection();
            //2.预编译sql语句,返回PreparedStatement的实例
            ps = connection.prepareStatement(sql);
            //3.填充占位符
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1,args[i]);
            }
            //4.执行
            ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //5.关闭资源
        JDBCUtils.closeResource(connection,ps);
    }

   

@Test
    public void testCommonUpdate(){
//        String sql1 = "delete from customers where id = ?";
//        update(sql1,3);

        String sql2 = "update `order` set order_name = ? where order_id = ?";
        update(sql2,"DD",2);
    }

四、Java与SQL对应数据类型转换表

五、数据的查询操作

*.ORM编程思想:(object relational mapping)

一个数据表对应一个java类

表中的一条记录对应java类的一个对象

表中的一个字段对应java类的一个属性

1.结果集ResultSet

2.基本的查询操作

@Test
    public void testQuery1(){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "select id,name,email,birth from customers where id = ?";
            ps = conn.prepareStatement(sql);

            ps.setObject(1,1);
            //执行,并返回结果集
            resultSet = ps.executeQuery();
            //处理结果集
            if (resultSet.next()){//判断结果集的吓一跳是否有数据,如果有数据,返回true并指针下移。如果返回false,则指针不下移
            //获取当前这条数据的各个字段值
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                String email = resultSet.getString(3);
                Date birth = resultSet.getDate(4);
                //方式一:
    //            System.out.println("id = " + id + ",name = " + name + ",email = " + email + ",birth = " + birth);
                //方式二:
    //            Object[] data = new Object[]{id,name,email,birth};
                //方式三:将数据封装为一个对象
                Customer customer = new Customer(id, name, email, birth);
                System.out.println(customer);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            //关闭资源
            JDBCUtils.closeResource(conn,ps,resultSet);
        }

    }

3.针对某一表的通用查询操作

@Test
    public void testQueryForCustomers(){
        String sql = "select id,name,birth,email from customers where id = ?";
        Customer customer = queryCustomers(sql,13);
        System.out.println(customer);

        String sql1 = "select name,email from customers where id = ?";
        Customer customer1 = queryCustomers(sql1,13);
        System.out.println(customer1);
    }

    //针对于customers表的查询操作
    public Customer queryCustomers(String sql,Object ...args){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();

            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1,args[i]);
            }

            rs = ps.executeQuery();
            //获取结果集的元数据
            ResultSetMetaData rsmd = rs.getMetaData();
            //通过ResultSetMetaData获取结果集中的列数
            int columnCount = rsmd.getColumnCount();
            if (rs.next()){
                Customer customer = new Customer();
                //处理结果集一行数据的每一个列
                for (int i = 0; i < columnCount; i++) {
                    //获取列值
                    Object columnvalue = rs.getObject(i + 1);

                    //获取每个列的列名
                    String columnName = rsmd.getColumnName(i + 1);

                    //给cust对象指定的某个属性,赋值为columnValue:通过反射
                    Field field = customer.getClass().getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(customer,columnvalue);
                }
                return customer;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            JDBCUtils.closeResource(conn,ps,rs);
        }
        return null;
    }

4.针对表的字段名和类的属性名不相同的操作

针对于表的字段名与类的属性名不相同的情况:
1.必须声明sql时,使用类的属性名来命名字段的别名
2.使用ResultSetMetaData时,需要使用getColumnLabel()来替换getColumnName()
说明:如果sql中没有给字段其别名:getColumnLable()获取的就是别名

/*
    * 针对于表的字段名与类的属性名不相同的情况:
    * 1.必须声明sql时,使用类的属性名来命名字段的别名
    * 2.使用ResultSetMetaData时,需要使用getColumnLabel()来替换getColumnName()
    *   说明:如果sql中没有给字段其别名:getColumnLable()获取的就是别名
    * */

    @Test
    public void testOrderForQuery(){
        String sql = "select order_id orderId,order_name orderName,order_date orderDate from `order` where order_id = ?";
        Order order = orderForQuery(sql,1);
        System.out.println(order);
    }

    //通用的针对于order表的查询操作
    public Order orderForQuery(String sql,Object ...args){
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1,args[i]);
            }
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            if (rs.next()){
                Order order = new Order();
                for (int i = 0; i < columnCount; i++) {
                    Object value = rs.getObject(i + 1);
                    //获取列的列名:getColumnName():--不推荐使用
                    //获取列的别名:getColumnLabel():
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    Field field = Order.class.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(order,value);
                }
                return order;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        JDBCUtils.closeResource(connection,ps,rs);
        return null;
    }
private int orderId;
    private String orderName;
    private Date orderDate;

    public Order() {
    }

    public Order(int orderId, String orderName, Date orderDate) {
        this.orderId = orderId;
        this.orderName = orderName;
        this.orderDate = orderDate;
    }

    public int getOrderId() {
        return orderId;
    }

    public void setOrderId(int orderId) {
        this.orderId = orderId;
    }

    public String getOrderName() {
        return orderName;
    }

    public void setOrderName(String orderName) {
        this.orderName = orderName;
    }

    public Date getOrderDate() {
        return orderDate;
    }

    public void setOrderDate(Date orderDate) {
        this.orderDate = orderDate;
    }

    @Override
    public String toString() {
        return "Order{" +
                "orderId=" + orderId +
                ", orderName='" + orderName + '\'' +
                ", orderDate=" + orderDate +
                '}';
    }

图解:

六、针对不同表的通用的查询操作

1.返回表中的一条记录

@Test
    public void testGetInstance(){
        String sql1 = "select id,name,email from customers where id = ?";
        Customer customer = getInstance(Customer.class, sql1, 12);
        System.out.println(customer);

        String sql2 = "select order_id orderId,order_name orderName,order_date orderDate from `order` where order_id = ?";
        Order order = getInstance(Order.class, sql2, 1);
        System.out.println(order);
    }

    public <T> T getInstance(Class<T> clazz,String sql,Object ...args){
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1,args[i]);
            }
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            if (rs.next()){
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    Object value = rs.getObject(i + 1);
                    //获取列的列名:getColumnName():--不推荐使用
                    //获取列的别名:getColumnLabel():
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t,value);
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        JDBCUtils.closeResource(connection,ps,rs);
        return null;
    }

2.返回表中多条记录的集合

@Test
    public void testGetInstance2(){
        String sql1 = "select id,name,email from customers where id < ?";
        List<Customer> list1 = getForList(Customer.class, sql1, 12);
        /*Iterator<Customer> iterator = list.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }*/
        list1.forEach(System.out::println);

        String sql2 = "select order_id orderId,order_name orderName,order_date orderDate from `order` where order_id < ?";
        List<Order> list2 = getForList(Order.class, sql2, 5);
        list2.forEach(System.out::println);
    }
public <T> List<T> getForList(Class<T> clazz,String sql,Object ...args){
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1,args[i]);
            }
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            //创建集合对象
            ArrayList<T> list = new ArrayList<>();
            while (rs.next()){
                T t = clazz.newInstance();
                //给t对象指定的属性赋值
                for (int i = 0; i < columnCount; i++) {
                    Object value = rs.getObject(i + 1);
                    //获取列的别名:getColumnLabel():
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t,value);
                }
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        JDBCUtils.closeResource(connection,ps,rs);
        return null;
    }

七、PreparedStatement有哪些好处?

1.PreparedStatement操作Blob的数据,而Statement做不到

2.PreparedStatement可以实现更高效的批量操作

3.可以解决sql注入问题

八、练习

练习1:

@Test
    public void testInsertData(){
        String sql = "insert into customers (name,email,birth) values (?,?,?)";
        int insertCount = cruMethod(sql,"Mbappe","mbappe@126.com","1992-09-08");//sql语言中'yyyy-MM-dd'隐式转换成java.sql.Date类型
        if (insertCount > 0){
            System.out.println("添加成功");
        } else {
            System.out.println("添加失败");
        }
    }

    public int cruMethod(String sql,Object ...args) {
        Connection connection = null;
        PreparedStatement ps = null;
        try {//建立连接,预编译sql语句
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {//填充占位符
                ps.setObject(i + 1,args[i]);
            }
            return ps.executeUpdate();//执行的是查询操作,有返回结果,此方法返回true;
            //执行的是增删改操作,没有返回结果,此方法返回false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        JDBCUtils.closeResource(connection,ps);//关闭资源
        return 0;
    }

练习2:

@Test
    public void testInsertData2(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入考生的详细信息:");
        System.out.print("Type:");
        int Type = scanner.nextInt();
        System.out.print("IDCard:");
        String IDCard = scanner.next();
        System.out.print("ExamCard:");
        String ExamCard = scanner.next();
        System.out.print("StudentName:");
        String StudentName = scanner.next();
        System.out.print("Location:");
        String Location = scanner.next();
        System.out.print("Grade:");
        int Grade = scanner.nextInt();
        String sql = "insert into examstudent (Type,IDCard,ExamCard,StudentName,Location,Grade) values (?,?,?,?,?,?)";

        if (update(sql,Type,IDCard,ExamCard,StudentName,Location,Grade) > 0){
            System.out.println("信息录入成功!");
        } else {
            System.out.println("信息录入失败!");
        }
    }

    public int update(String sql,Object ...args){
        Connection connection = null;//建立连接
        PreparedStatement ps = null;//预编译sql语句
        try {
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {//填充占位符
                ps.setObject(i + 1,args[i]);
            }
            return ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        JDBCUtils.closeResource(connection,ps);//关闭资源
        return 0;
    }

练习3:

第 4 章 操作BLOB类型字段

4.1 Oracle LOB介绍

LOB,即Large Objects(大对象),是用来存储大量的二进制和文本数据的一种数据类 型(一个LOB字段可存储可多达4GB的数据)。

LOB 分为两种类型:内部LOB和外部LOB。

内部LOB将数据以字节流的形式存储在数据库的内部。因而,内部LOB的许多操作都 可以参与事务,也可以像处理普通数据一样对其进行备份和恢复操作。Oracle支持三 种类型的内部LOB:

BLOB(二进制数据)

CLOB(单字节字符数据)

NCLOB(多字节字符数据)

CLOB和NCLOB类型适用于存储超长的文本数据,BLOB字段适用于存储大量的二进 制数据,如图像、视频、音频,文件等。

目前只支持一种外部LOB类型,即BFILE类型。在数据库内,该类型仅存储数据在操 作系统中的位置信息,而数据的实体以外部文件的形式存在于操作系统的文件系统中。 因而,该类型所表示的数据是只读的,不参与事务。该类型可帮助用户管理大量的由 外部程序访问的文件。

4.2 Mysql BLOB类型

4.3 向数据表中插入大数据类型

//向customers表中插入Blob类型的字段
    @Test
    public void testInsertMethod() {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            connection = JDBCUtils.getConnection();
            String sql = "insert into customers(name,email,birth,photo)values(?,?,?,?) ";
            ps = connection.prepareStatement(sql);

            ps.setObject(1,"张邵忠");
            ps.setObject(2,"zhang@qq.com");
            ps.setObject(3,"1999-12-12");
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("picture.jpg")));
            ps.setBlob(4,bis);

            ps.execute();

            if (bis != null){
                bis.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection,ps);
        }
    }

4.4 从数据表中读取大数据类型

//查询数据表customers中Blob类型的字段
    @Test
    public void testQuery(){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "select id,name,email,birth,photo from customers where id = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1,16);

            rs = ps.executeQuery();
            if (rs.next()){
                int id = rs.getInt(1);
                String name = rs.getString(2);
                String email = rs.getString(3);
                Date birth = rs.getDate(4);

                Customer customer = new Customer(id, name, email, birth);
                System.out.println(customer);

                //将Blob类型的字段下载下来,以文件的方式保存在本地
                Blob photo = rs.getBlob(5);
                InputStream is = photo.getBinaryStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("picture1.jpg")));
                byte[] buffer = new byte[1024];
                int len;
                while ((len = bis.read(buffer)) != -1){
                    bos.write(buffer,0,len);
                }
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        JDBCUtils.closeResource(conn,ps,rs);

    }

4.5 插入Blob字段特殊情况的说明

第 5 章 批量插入

5.1 批量插入的说明

当需要成批插入或者更新记录时。可以采用Java的批量更新机制,这 一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单 独提交处理更有效率

JDBC的批量处理语句包括下面两个方法:

addBatch(String):添加需要批量处理的SQL语句或是参数;

executeBatch():执行批量处理语句;

clearBatch():清空缓存的数据

通常我们会遇到两种批量执行SQL语句的情况:

多条SQL语句的批量处理;

一个SQL语句的批量传参;

5.2 实现批量插入

题目:

向goods表中插入20000条数据

方式一:使用Statement

方式二:使用PreparedStatement

//批量插入数据:使用PreparedStatement
    @Test
    public void testInsert1(){
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            connection = JDBCUtils.getConnection();
            String sql = "insert into goods(name)values(?)";
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < 20000; i++) {
                ps.setObject(1,"name_" + i);
                ps.execute();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection,ps);
        }
    }

5.3 批量插入操作的优化

//批量插入数据的方式四:
    //1.addBatch()、executeBatch()、clearBatch()
    //2.Mysql服务器默认是关闭批处理的,让mysql开启批处理的支持。
    //?rewriteBatchedStatements=true写在配置文件的url的后面
    //3.使用更新的mysql驱动:mysql-connector-java-5.1.37-bin.jar
    @Test
    public void test4(){
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            connection = JDBCUtils.getConnection();
            //设置不允许自动提交数据
            connection.setAutoCommit(false);
            String sql = "insert into goods(name)values(?)";
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < 1000000; i++) {
                ps.setObject(1,"name_" + i);
                //1."攒"sql
                ps.addBatch();
                if ((i + 1) % 500 == 0){
                    //2.执行batch
                    ps.executeBatch();
                    //3.清空batch
                    ps.clearBatch();
                }
            }
            connection.commit();
            //20000:28120 -> 1388
            //1000000:8638 -> 7143
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection,ps);
        }
    }

PreparedStatement 和 Statement的区别

1.PreparedStatement避免了拼串操作,编写sql语句更简洁,效率更高

2.PreparedStatement防止sql注入问题:原因

3.PreparedStatement语句可以最大可能提高性能

//4.PreparedStatement语句可以操作大文件(Statement语句应该也可以吧)

第 6 章 数据库事务

6.1 数据库事务介绍

1.事务:一组逻辑操作单元,使数据从一种状态变换到另一种状态。

2.事务处理(事务操作):保证所有事务都作为一个工作单元来执行,即 使出现了故障,都不能改变这种执行方式。当在一个事务中执行多个操作时,要么所有的事务都被提交(commit),那么这些修改就永久地保存下来;要么数据库管理系统将放弃所作的所有修改,整个事务回滚 (rollback)到最初状态。

3.数据一旦提交就不可回滚

4.哪些操作会导致数据的自动提交?

1)DDL操作一旦执行,都会自动提交

set autocommit = false对DDL操作失效

2)DML操作默认情况下,一旦执行也会自动提交。

我们可以通过set autocommit = false的方式取消DML的自动提交

3)默认在关闭连接时,会自动的提交数据

为确保数据库中数据的一致性,数据的操纵应当是离散的成组的逻辑单元: 当它全部完成时,数据的一致性可以保持,而当这个单元中的一部分操作 失败,整个事务应全部视为错误,所有从起始点以后的操作应全部回退到 开始状态。

6.2 JDBC事务处理

方法实现:

@Test
    public void testUpdateTransaction(){
        Connection connection = null;
        try {
            connection = JDBCUtils.getConnection();
            //1.取消数据的自动提交功能
            connection.setAutoCommit(false);
            String sql1 = "update user_table set balance = balance - 100 where user = ?";
            update(connection,sql1,"AA");
            //模拟网络异常
            System.out.println(10 / 0);
            String sql2 = "update user_table set balance = balance + 100 where user = ?";
            update(connection,sql2,"BB");
            System.out.println("转账成功");
        } catch (Exception e) {
            e.printStackTrace();
            //2.回滚数据
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {//3.提交,并设置连接回复为默认值(主要针对使用数据库连接池时的使用)
            try {
                connection.commit();
                connection.setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JDBCUtils.closeResource(connection,null);//关闭资源
        }
    }

    //通用的增删改操作 --- version2.0
    public int update(Connection connection,String sql,Object ...args){
        PreparedStatement ps = null;//预编译sql语句
        try {//1.预编译sql语句
            ps = connection.prepareStatement(sql);
            //2.填充占位符
            for (int i = 0; i < args.length; i++) {//填充占位符
                ps.setObject(i + 1,args[i]);
            }//3.执行
            return ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }//4.关闭资源
        JDBCUtils.closeResource(null,ps);//关闭资源
        return 0;
    }

6.3 事务的ACID属性

事务的ACID(acid)属性

1. 原子性(Atomicity) 原子性是指事务是一个不可分割的工作单位,事务中的操作要么都发生,要么都不 发生。

2. 一致性(Consistency) 事务必须使数据库从一个一致性状态变换到另外一个一致性状态。

3. 隔离性(Isolation) 事务的隔离性是指一个事务的执行不能被其他事务干扰,即一个事务内部的操作及 使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。

4. 持久性(Durability) 持久性是指一个事务一旦被提交,它对数据库中数据的改变就是永久性的,接下来 的其他操作和数据库故障不应该对其有任何影响

6.3.1 数据库的并发问题

对于同时运行的多个事务, 当这些事务访问数据库中相同的数据时, 如果没有采取必要的 隔离机制, 就会导致各种并发问题:

    • 脏读: 对于两个事务 T1, T2, T1 读取了已经被 T2 更新但还没有被提交的字段。之后, 若 T2 回 滚, T1读取的内容就是临时且无效的。
    • 不可重复读: 对于两个事务T1, T2, T1 读取了一个字段, 然后 T2 更新了该字段。之后, T1再次 读取同一个字段, 值就不同了。
    • 幻读: 对于两个事务T1, T2, T1 从一个表中读取了一个字段, 然后 T2 在该表中插入了一些新的 行。之后, 如果 T1 再次读取同一个表, 就会多出几行。

数据库事务的隔离性: 数据库系统必须具有隔离并发运行各个事务的能力, 使它们不会相 互影响, 避免各种并发问题。

一个事务与其他事务隔离的程度称为隔离级别. 数据库规定了多种事务隔离级别, 不同隔 离级别对应不同的干扰程度, 隔离级别越高, 数据一致性就越好, 但并发性越弱。

6.3.2 四种隔离级别

6.3.3 在MySQL中设置隔离级别

第 7 章 DAO及其实现类

DAO:database access object 数据库操作对象

BaseDAO.java

public abstract class BaseDAO {
    //通用的增删改操作 --- version2.0
    public int update(Connection connection, String sql, Object ...args){
        PreparedStatement ps = null;//预编译sql语句
        try {//1.预编译sql语句
            ps = connection.prepareStatement(sql);
            //2.填充占位符
            for (int i = 0; i < args.length; i++) {//填充占位符
                ps.setObject(i + 1,args[i]);
            }//3.执行
            return ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }//4.关闭资源
        JDBCUtils.closeResource(null,ps);//关闭资源
        return 0;
    }


    //通用的查询操作,用于返回数据表中的一条记录(version2.0,考虑上事务)
    public <T> T getInstance(Connection connection,Class<T> clazz,String sql,Object ...args ){
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1,args[i]);
            }
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            if (rs.next()){
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    Object value = rs.getObject(i + 1);
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t,value);
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        JDBCUtils.closeResource(null,ps,rs);
        return null;
    }
    //通用的查询操作,用于返回数据表中的多条记录的集合(version2.0,考虑上事务)
    public <T> List<T> getForList(Connection connection,Class<T> clazz, String sql, Object ...args){
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1,args[i]);
            }
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            //创建集合对象
            ArrayList<T> list = new ArrayList<>();
            while (rs.next()){
                T t = clazz.newInstance();
                //给t对象指定的属性赋值
                for (int i = 0; i < columnCount; i++) {
                    Object value = rs.getObject(i + 1);
                    //获取列的别名:getColumnLabel():
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t,value);
                }
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        JDBCUtils.closeResource(null,ps,rs);
        return null;
    }

    public <E> E getValue(Connection connection,String sql,Object ...args){
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1,args[i]);
            }
            rs = ps.executeQuery();
            if (rs.next()){
                return (E) rs.getObject(1);//此方法返回返回值类型,(E)隐式判断为此返回值类型
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(null,ps,rs);
        }
        return null;
    }
}
/**
 * @author 张丁野
 * @version v1.0
 * @time 2022-07-25-16:16
 * @Description
 * 此接口用于规范针对于customers表的常用操作
 */
public interface CustomerDAO {
    //将cust对象添加到数据库中
    void insert(Connection connection, Customer customer);
    //根据指定的id删除表中的一条记录
    void deleteById(Connection connection,int id);
    //针对于内存中的cust对象,去修改数据表中指定的记录
    void update(Connection connection,Customer customer);
    //针对指定的id查询对应的Customer对象
    Customer getCustomerById(Connection connection,int id);
    //查询表中的所有的记录构成的集合
    List<Customer> getAll(Connection connection);
    //返回数据表中数据的条目数
    Long getCount(Connection connection);
    //返回数据表中最大的生日
    Date getMaxBirth(Connection connection);
}
public class CustomerDAOImpl extends BaseDAO<Customer> implements CustomerDAO {



    @Override
    public void insert(Connection connection, Customer customer) {
        String sql = "insert into customers(name,email,birth) values(?,?,?)";
        update(connection,sql,customer.getName(),customer.getEmail(),customer.getBirth());
    }

    @Override
    public void deleteById(Connection connection, int id) {
        String sql = "delete from customers where id = ?";
        update(connection,sql,id);
    }

    @Override
    public void update(Connection connection, Customer customer) {
        String sql = "update customers set name = ?,email = ?,birth = ? where id = ?";
        update(connection,sql, customer.getName(),customer.getEmail(),customer.getBirth(),customer.getId());
    }

    @Override
    public Customer getCustomerById(Connection connection, int id) {
        String sql = "select id,name,email,birth from customers where id = ?";
        Customer customer = getInstance(connection, sql, id);
        return customer;
    }

    @Override
    public List<Customer> getAll(Connection connection) {
        String sql = "select id,name,email,birth from customers";
        List<Customer> list = getForList(connection, sql);
        return list;
    }

    @Override
    public Long getCount(Connection connection) {
        String sql = "select count(*) from customers";
        return getValue(connection, sql);
    }

    @Override
    public Date getMaxBirth(Connection connection) {
        String sql = "select max(birth) from customers";
        return getValue(connection,sql);

    }
}

第 8 章 数据库连接池

8.1 数据库连接池的必要性

在使用开发基于数据库的web程序时,传统的模式基本是按以下步骤:

      • 在主程序(如servlet、beans)中建立数据库连接
      • 进行sql操作
      • 断开数据库连接

这种模式开发,存在的问题:

      • 普通的JDBC数据库连接使用 DriverManager 来获取,每次向数据库建立连接的时候都要将 Connection 加载到内存中,再验证用户名和密码(得花费0.05s~1s的时间)。需要数据库连接的时 候,就向数据库要求一个,执行完成后再断开连接。这样的方式将会消耗大量的资源和时间。数据库的连接资源并没有得到很好的重复利用.若同时有几百人甚至几千人在线,频繁的进行数据库 连接操作将占用很多的系统资源,严重的甚至会造成服务器的崩溃。
      • 对于每一次数据库连接,使用完后都得断开。否则,如果程序出现异常而未能关闭,将会导致数据库系统中的内存泄漏,最终将导致重启数据库。
      • 这种开发不能控制被创建的连接对象数,系统资源会被毫无顾及的分配出去,如连接过多,也可能导致内存泄漏,服务器崩溃

8.2 数据库连接池技术

为解决传统开发中的数据库连接问题,可以采用数据库连接池技术。

数据库连接池的基本思想就是为数据库连接建立一个“缓冲池”。预先在缓冲 池中放入一定数量的连接,当需要建立数据库连接时,只需从“缓冲池”中取 出一个,使用完毕之后再放回去。

数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一 个现有的数据库连接,而不是重新建立一个。

数据库连接池在初始化时将创建一定数量的数据库连接放到连接池中,这些数 据库连接的数量是由最小数据库连接数来设定的。无论这些数据库连接是否被 使用,连接池都将一直保证至少拥有这么多的连接数量。连接池的最大数据库连接数量限定了这个连接池能占有的最大连接数,当应用程序向连接池请求的 连接数超过最大连接数量时,这些请求将被加入到等待队列中。

8.3 数据库连接池技术的优点

1.资源重用

由于数据库连接得以重用,避免了频繁创建,释放连接引起的大量性能开销。在减少系统消耗 的基础上,另一方面也增加了系统运行环境的平稳性。

2.更快的系统反应速度

数据库连接池在初始化过程中,往往已经创建了若干数据库连接置于连接池中备用。此时连接 的初始化工作均已完成。对于业务请求处理而言,直接利用现有可用连接,避免了数据库连接 初始化和释放过程的时间开销,从而减少了系统的响应时间

3.新的资源分配手段

对于多应用共享同一数据库的系统而言,可在应用层通过数据库连接池的配置,实现某一应用 最大可用数据库连接数的限制,避免某一应用独占所有的数据库资源

4.统一的连接管理,避免数据库连接泄露

在较为完善的数据库连接池实现中,可根据预先的占用超时设定,强制回收被占用连接,从而 避免了常规数据库连接操作中可能出现的资源泄露

8.4 多种开源的数据库连接池

  • JDBC 的数据库连接池使用 javax.sql.DataSource 来表示,DataSource 只是一个接口,该接口通常由服务器(Weblogic, WebSphere, Tomcat)提供实现,也有一些开源组织提供实现:
    • DBCP 是Apache提供的数据库连接池。tomcat 服务器自带dbcp数据库连接池。速度相对c3p0较快,但因自身存在BUG,Hibernate3已不再提供支持。
    • C3P0 是一个开源组织提供的一个数据库连接池,速度相对较慢,稳定性还可以。hibernate官方推荐使用
    • Proxool 是sourceforge下的一个开源项目数据库连接池,有监控连接池状态的功能,稳定性较c3p0差一点
    • BoneCP 是一个开源组织提供的数据库连接池,速度快
    • Druid 是阿里提供的数据库连接池,据说是集DBCP 、C3P0 、Proxool 优点于一身的数据库连接池,但是速度不确定是否有BoneCP快
  • DataSource 通常被称为数据源,它包含连接池和连接池管理两个部分,习惯上也经常把 DataSource 称为连接池
  • DataSource用来取代DriverManager来获取Connection,获取速度快,同时可以大幅度提高数据库访问速度。
  • 特别注意:
    • 数据源和数据库连接不同,数据源无需创建多个,它是产生数据库连接的工厂,因此整个应用只需要一个数据源即可。
    • 当数据库访问结束后,程序还是像以前一样关闭数据库连接:conn.close(); 但conn.close()并没有关闭数据库的物理连接,它仅仅把数据库连接释放,归还给了数据库连接池。

c3p0连接池

使用c3p0连接池创建并管理连接

xml配置文件在

public class C3P0Test {

    //方式一:硬编码的方式,不推荐
    @Test
    public void testGetConnection() throws Exception {
        //获取c3p0数据库连接池
        ComboPooledDataSource cpds = new ComboPooledDataSource();
        cpds.setDriverClass( "com.mysql.cj.jdbc.Driver" ); //loads the jdbc driver
        cpds.setJdbcUrl( "jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true" );
        cpds.setUser("root");
        cpds.setPassword("Zdy!230003#");
        //通过设置相关的参数,对数据库连接池进行管理
        //设置初始时数据库连接池中的连接数
        cpds.setInitialPoolSize(10);

        Connection connection = cpds.getConnection();
        System.out.println(connection);

        //销毁c3p0连接池
//        DataSources.destroy(cpds);
    }

    //方式二:使用配置文件
    @Test
    public void testGetConnection1() throws SQLException {
        ComboPooledDataSource cpds = new ComboPooledDataSource("helloc3p0");
        Connection connection = cpds.getConnection();
        System.out.println(connection);
    }
}
<?xml version="1.0" encoding="utf-8" ?>
<c3p0-config>

    <!-- This app is massive! -->
    <named-config name="helloc3p0">
        <!-- 提供获取连接的4个基本信息 -->
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true</property>
        <property name="user">root</property>
        <property name="password">Zdy!230003#</property>

        <!-- 进行数据库连接池管理的基本信息 -->
        <!-- 当数据库连接池中的连接数不够时,c3p0一次性向数据库服务器中申请的连接数 -->
        <property name="acquireIncrement">50</property>
        <!-- c3p0数据库连接池中初始化时的连接数 -->
        <property name="initialPoolSize">100</property>
        <!--c3p0数据库连接池维护的最少的连接数-->
        <property name="minPoolSize">50</property>
        <!--c3p0数据库连接池维护的最多的连接数-->
        <property name="maxPoolSize">1000</property>

        <!-- intergalactoApp adopts a different approach to configuring statement caching -->
        <!-- c3p0连接池最多维护的Statement的个数 -->
        <property name="maxStatements">50</property>
        <!-- 每一个连接中可以最多使用的Statement的个数 -->
        <property name="maxStatementsPerConnection">5</property>
    </named-config>
</c3p0-config>

JDBCUtils方法实现:

//使用c3p0数据库连接池技术获取数据库连接
    //数据库连接池只提供一个即可
    private static ComboPooledDataSource cpds = new ComboPooledDataSource("helloc3p0");
    public static Connection getConnection() throws SQLException {
        Connection connection = cpds.getConnection();
        return  connection;
    }

xml配置文件模板:

<c3p0-config>
  <default-config>
    <property name="automaticTestTable">con_test</property>
    <property name="checkoutTimeout">30000</property>
    <property name="idleConnectionTestPeriod">30</property>
    <property name="initialPoolSize">10</property>
    <property name="maxIdleTime">30</property>
    <property name="maxPoolSize">100</property>
    <property name="minPoolSize">10</property>
    <property name="maxStatements">200</property>

    <user-overrides user="test-user">
      <property name="maxPoolSize">10</property>
      <property name="minPoolSize">1</property>
      <property name="maxStatements">0</property>
    </user-overrides>

  </default-config>

  <!-- This app is massive! -->
  <named-config name="intergalactoApp"> 
    <property name="acquireIncrement">50</property>
    <property name="initialPoolSize">100</property>
    <property name="minPoolSize">50</property>
    <property name="maxPoolSize">1000</property>

    <!-- intergalactoApp adopts a different approach to configuring statement caching -->
    <property name="maxStatements">0</property> 
    <property name="maxStatementsPerConnection">5</property>

    <!-- he's important, but there's only one of him -->
    <user-overrides user="master-of-the-universe"> 
      <property name="acquireIncrement">1</property>
      <property name="initialPoolSize">1</property>
      <property name="minPoolSize">1</property>
      <property name="maxPoolSize">5</property>
      <property name="maxStatementsPerConnection">50</property>
    </user-overrides>
  </named-config>
</c3p0-config>

dbcp连接池

使用dbcp连接池创建并管理连接

public class DBCPTest {
    //测试DBCP的数据库连接池技术

    //方式一:不推荐
    @Test
    public void testGetConnection()throws Exception{
        //创建了DBCP的数据库连接池
        BasicDataSource source = new BasicDataSource();

        //设置基本信息
        source.setDriverClassName("com.mysql.cj.jdbc.Driver");
        source.setUrl("jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true");
        source.setUsername("root");
        source.setPassword("Zdy!230003#");

        //还可以设置其他设计数据库连接池管理的一些属性
        source.setInitialSize(10);

        Connection connection = source.getConnection();
        System.out.println(connection);
    }

    //方式二:使用配置文件
    @Test
    public void getConnection2()throws Exception{
        Properties pros = new Properties();
        InputStream ras = ClassLoader.getSystemClassLoader().getResourceAsStream("dbcp.properties");
        pros.load(ras);
        BasicDataSource source = BasicDataSourceFactory.createDataSource(pros);

        Connection connection = source.getConnection();
        System.out.println(connection);
    }
}

JDBCUtils方法实现:

//使用dbcp数据库连接池技术获取数据库连接
    private static BasicDataSource source;
    static{
        try {
            Properties pros = new Properties();
            InputStream ras = ClassLoader.getSystemClassLoader().getResourceAsStream("dbcp.properties");
            pros.load(ras);
            source = BasicDataSourceFactory.createDataSource(pros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection2()throws Exception{
        Connection connection = source.getConnection();
        return connection;
    }

Druid数据库连接池

@Test
    public void getConnection() throws Exception{
        Properties pros = new Properties();
        InputStream ras = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
        pros.load(ras);
        DataSource source = DruidDataSourceFactory.createDataSource(pros);
        Connection connection = source.getConnection();
        System.out.println(connection);
    }
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true
username=root
password=Zdy!230003#
initialSize=8

JDBCUtils方法实现:

//使用druid数据库连接池技术获取数据库连接
    private static DruidDataSource druidDataSource;
    static{
        try {
            Properties pros = new Properties();
            InputStream ras = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
            pros.load(ras);
            druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(pros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection3() throws Exception{
        Connection connection = druidDataSource.getConnection();
        return connection;
    }

第 9 章 Apache-DBUtils实现CRUD操作

commons-dbutils 是 Apache 组织提供的一个开源JDBC工具类库,封装了针对于数据库的增删改查操作

9.2.1 DbUtils

  • DbUtils :提供如关闭连接、装载JDBC驱动程序等常规工作的工具类,里面的所有方法都是静态的。主要方法如下:
    • public static void close(…) throws java.sql.SQLException: DbUtils类提供了三个重载的关闭方法。这些方法检查所提供的参数是不是NULL,如果不是的话,它们就关闭Connection、Statement和ResultSet。
    • public static void closeQuietly(…): 这一类方法不仅能在Connection、Statement和ResultSet为NULL情况下避免关闭,还能隐藏一些在程序中抛出的SQLEeception。
    • public static void commitAndClose(Connection conn)throws SQLException: 用来提交连接的事务,然后关闭连接
    • public static void commitAndCloseQuietly(Connection conn): 用来提交连接,然后关闭连接,并且在关闭连接时不抛出SQL异常。
    • public static void rollback(Connection conn)throws SQLException:允许conn为null,因为方法内部做了判断
    • public static void rollbackAndClose(Connection conn)throws SQLException
    • rollbackAndCloseQuietly(Connection)
    • public static boolean loadDriver(java.lang.String driverClassName):这一方装载并注册JDBC驱动程序,如果成功就返回true。使用该方法,你不需要捕捉这个异常ClassNotFoundException。

9.2.2 QueryRunner类

  • 该类简单化了SQL查询,它与ResultSetHandler组合在一起使用可以完成大部分的数据库操作,能够大大减少编码量。
  • QueryRunner类提供了两个构造器:
    • 默认的构造器
    • 需要一个 javax.sql.DataSource 来作参数的构造器
  • QueryRunner类的主要方法:
    • 更新
      • public int update(Connection conn, String sql, Object... params) throws SQLException:用来执行一个更新(插入、更新或删除)操作。
      • ......
    • 插入
      • public  T insert(Connection conn,String sql,ResultSetHandler rsh, Object... params) throws SQLException:只支持INSERT语句,其中 rsh - The handler used to create the result object from the ResultSet of auto-generated keys.  返回值: An object generated by the handler.即自动生成的键值
      • ....
    • 批处理
      • public int[] batch(Connection conn,String sql,Object[][] params)throws SQLException: INSERT, UPDATE, or DELETE语句
      • public  T insertBatch(Connection conn,String sql,ResultSetHandler rsh,Object[][] params)throws SQLException:只支持INSERT语句
      • .....
    • 查询
      • public Object query(Connection conn, String sql, ResultSetHandler rsh,Object... params) throws SQLException:执行一个查询操作,在这个查询中,对象数组中的每个元素值被用来作为查询语句的置换参数。该方法会自行处理 PreparedStatement 和 ResultSet 的创建和关闭。
      • ......
  • 测试

// 测试添加
@Test
public void testInsert() throws Exception {
	QueryRunner runner = new QueryRunner();
	Connection conn = JDBCUtils.getConnection3();
	String sql = "insert into customers(name,email,birth)values(?,?,?)";
	int count = runner.update(conn, sql, "何成飞", "he@qq.com", "1992-09-08");

	System.out.println("添加了" + count + "条记录");
		
	JDBCUtils.closeResource(conn, null);

}

// 测试删除
@Test
public void testDelete() throws Exception {
	QueryRunner runner = new QueryRunner();
	Connection conn = JDBCUtils.getConnection3();
	String sql = "delete from customers where id < ?";
	int count = runner.update(conn, sql,3);

	System.out.println("删除了" + count + "条记录");
		
	JDBCUtils.closeResource(conn, null);

}

9.2.3 ResultSetHandler接口及实现类

  • 该接口用于处理 java.sql.ResultSet,将数据按要求转换为另一种形式。
  • ResultSetHandler 接口提供了一个单独的方法:Object handle (java.sql.ResultSet .rs)。
  • 接口的主要实现类:
    • ArrayHandler:把结果集中的第一行数据转成对象数组。
    • ArrayListHandler:把结果集中的每一行数据都转成一个数组,再存放到List中。
    • BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。
    • BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。
    • ColumnListHandler:将结果集中某一列的数据存放到List中。
    • KeyedHandler(name):将结果集中的每一行数据都封装到一个Map里,再把这些map再存到一个map里,其key为指定的key。
    • MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
    • MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List
    • ScalarHandler:查询单个值对象
  • 测试

/*
 * 测试查询:查询一条记录
 * 
 * 使用ResultSetHandler的实现类:BeanHandler
 */
@Test
public void testQueryInstance() throws Exception{
	QueryRunner runner = new QueryRunner();

	Connection conn = JDBCUtils.getConnection3();
		
	String sql = "select id,name,email,birth from customers where id = ?";
		
	//
	BeanHandler<Customer> handler = new BeanHandler<>(Customer.class);
	Customer customer = runner.query(conn, sql, handler, 23);
	System.out.println(customer);	
	JDBCUtils.closeResource(conn, null);
}

/*
 * 测试查询:查询多条记录构成的集合
 * 
 * 使用ResultSetHandler的实现类:BeanListHandler
 */
@Test
public void testQueryList() throws Exception{
	QueryRunner runner = new QueryRunner();

	Connection conn = JDBCUtils.getConnection3();
		
	String sql = "select id,name,email,birth from customers where id < ?";
		
	//
	BeanListHandler<Customer> handler = new BeanListHandler<>(Customer.class);
	List<Customer> list = runner.query(conn, sql, handler, 23);
	list.forEach(System.out::println);
		
	JDBCUtils.closeResource(conn, null);
}

/*
 * 自定义ResultSetHandler的实现类
 */
@Test
public void testQueryInstance1() throws Exception{
	QueryRunner runner = new QueryRunner();

	Connection conn = JDBCUtils.getConnection3();
		
	String sql = "select id,name,email,birth from customers where id = ?";
		
	ResultSetHandler<Customer> handler = new ResultSetHandler<Customer>() {

		@Override
		public Customer handle(ResultSet rs) throws SQLException {
			System.out.println("handle");
//			return new Customer(1,"Tom","tom@126.com",new Date(123323432L));
				
			if(rs.next()){
				int id = rs.getInt("id");
				String name = rs.getString("name");
				String email = rs.getString("email");
				Date birth = rs.getDate("birth");
					
				return new Customer(id, name, email, birth);
			}
			return null;
				
		}
	};
		
	Customer customer = runner.query(conn, sql, handler, 23);
		
	System.out.println(customer);
		
	JDBCUtils.closeResource(conn, null);
}

/*
 * 如何查询类似于最大的,最小的,平均的,总和,个数相关的数据,
 * 使用ScalarHandler
 * 
 */
@Test
public void testQueryValue() throws Exception{
	QueryRunner runner = new QueryRunner();

	Connection conn = JDBCUtils.getConnection3();
		
	//测试一:
//	String sql = "select count(*) from customers where id < ?";
//	ScalarHandler handler = new ScalarHandler();
//	long count = (long) runner.query(conn, sql, handler, 20);
//	System.out.println(count);
		
	//测试二:
	String sql = "select max(birth) from customers";
	ScalarHandler handler = new ScalarHandler();
	Date birth = (Date) runner.query(conn, sql, handler);
	System.out.println(birth);
		
	JDBCUtils.closeResource(conn, null);
}

JDBC总结

总结
@Test
public void testUpdateWithTx() {
		
	Connection conn = null;
	try {
		//1.获取连接的操作(
		//① 手写的连接:JDBCUtils.getConnection();
		//② 使用数据库连接池:C3P0;DBCP;Druid
		//2.对数据表进行一系列CRUD操作
		//① 使用PreparedStatement实现通用的增删改、查询操作(version 1.0 \ version 2.0)
//version2.0的增删改public void update(Connection conn,String sql,Object ... args){}
//version2.0的查询 public <T> T getInstance(Connection conn,Class<T> clazz,String sql,Object ... args){}
		//② 使用dbutils提供的jar包中提供的QueryRunner类
			
		//提交数据
		conn.commit();
			
	
	} catch (Exception e) {
		e.printStackTrace();
			
			
		try {
			//回滚数据
			conn.rollback();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
			
	}finally{
		//3.关闭连接等操作
		//① JDBCUtils.closeResource();
		//② 使用dbutils提供的jar包中提供的DbUtils类提供了关闭的相关操作
			
	}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值