ApacheDBUtils 详解用法

文章目录

    • Dbutils 是什么?
    • 为什么需要Dbutils ?
    • Dbutils三个核心类介绍:
      • 1:DbUtils:连接数据库对象----jdbc辅助方法的集合类,线程安全
      • 2:QueryRunner:SQL语句的操作对象,可以设置查询结果集的封装策略,线程安全。
      • (3)ResultSetHandle:封装数据的策略对象------将封装结果集中的数据,转换到另一个对象
    • 实现步骤:
    • 代码展示:

Dbutils 是什么?

DataBaseUtils主要是封装了 JDBC 的操作代码,简化 Dao 层的操作。
它能够更好的帮助我们的开发,提升开发的效率,同时,减少了大量的重复代码。

为什么需要Dbutils ?

在使用Dbutils 之前,我们Dao层使用的技术是JDBC,那么分析一下JDBC的弊端:
(1)数据库链接对象、sql语句操作对象,封装结果集对象,这三大对象会重复定义
(2)封装数据的代码重复,而且操作复杂,代码量大
(3)释放资源的代码重复
结果:(1)程序员在开发的时候,有大量的重复劳动。(2)开发的周期长,效率低

Dbutils三个核心类介绍:

1:DbUtils:连接数据库对象----jdbc辅助方法的集合类,线程安全

      构造方法:DbUtils()
      作用:控制连接,控制书屋,控制驱动加载额一个类。

2:QueryRunner:SQL语句的操作对象,可以设置查询结果集的封装策略,线程安全。

构造方法

(1)QueryRunner():创建一个与数据库无关的QueryRunner对象,后期再操作数据库的会后,需要手动给一个Connection对象,它可以手动控制事务。
Connection.setAutoCommit(false); 设置手动管理事务
Connection.commit(); 提交事务

(2)QueryRunner(DataSource ds):创建一个与数据库关联的queryRunner对象,后期再操作数据库的时候,不需要Connection对象,自动管理事务。
DataSource:数据库连接池对象。

构造函数与增删改查方法的组合:
QueryRunner()
update(Connection conn, String sql, Object… params)
query(Connection conn, String sql, ResultSetHandler rsh, Object… params)

QueryRunner(DataSource ds):已经连接了就不需要再连接了。
update(String sql, Object… params)
query(String sql, ResultSetHandler rsh, Object… params)

(3)ResultSetHandle:封装数据的策略对象------将封装结果集中的数据,转换到另一个对象

策略:封装数据到对象的方式(示例:将数据库保存在User、保存到数组、保存到集合)
方法介绍:handle(ResultSet rs)
这是一个接口,主要是通过其实现类进行各种操作,作为我们的返回值对象

QueryRunner runner = new QueryRunner(DataSourceUtil.getDateSourceWithC3P0ByConfig());
// 执行 SQL 语句,后面的参数是可变的,参数较多时可以用 Object 数组进行传递。
 // new ArrayHandler() 是 ResultSetHandle 的一个实现类,交代我们的返回值类型。
Object[] student = runner.query("select * from student where sno > ?", new ArrayHandler(), 1);

实现步骤:

1、需要下载相关的 jar 包: cp30,commons-dbutls,mysql驱动。
2、如果用数据源需要有个连接池: c3p0-config.xml 文件。
3、代码实现。

代码展示:

c3p0-config.xml – 连接池配置文件:



<c3p0-config>

    
    <default-config>
        <property name="user">rootproperty>
        <property name="password">rootproperty>
        <property name="driverClass">com.mysql.cj.jdbc.Driverproperty>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/sqltest?&useSSL=false&serverTimezone=UTCproperty>

    default-config>

    
    
        <property name="user">rootproperty>
        <property name="password">rootproperty>
        <property name="driverClass">com.mysql.cj.jdbc.Driverproperty>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/sqltest?&useSSL=false&serverTimezone=UTCproperty>

    named-config>


c3p0-config>

DataSorceUtil.java – 连接池帮助类:

package rj.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.Properties;

public class DataSourceUtil {
    public static DataSource getDataSourceWithC3P0() throws PropertyVetoException {
        ComboPooledDataSource c3p0 = new ComboPooledDataSource();
        c3p0.setDriverClass("com.mysql.cj.jdbc.Driver");
        c3p0.setJdbcUrl("jdbc:mysql://localhost:3306/sqltest?serverTimezone=GMT%2B8");
        c3p0.setUser("root");
        c3p0.setPassword("root");

        return c3p0;
    }


    public static DataSource getDateSourceWithC3P0ByConfig() {
        ComboPooledDataSource c3p0 = new ComboPooledDataSource("rj");
        return c3p0;
    }

    public static DataSource getDataSourceWithDBCP() {
        BasicDataSource dbcp = new BasicDataSource();

        dbcp.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dbcp.setUrl("jdbc:mysql://localhost:3306/sqltest?serverTimezone=GMT%2B8");
        dbcp.setUsername("root");
        dbcp.setPassword("root");
        dbcp.setInitialSize(20);
        dbcp.setMaxActive(10);

        return dbcp;
    }

    public static DataSource getDataSourceWithDBCPByProperties() throws Exception {
        DataSource dbcp = null;
        Properties properties = new Properties();

        InputStream input = new DBCPDemo().getClass().getClassLoader().getResourceAsStream("dbcpconfig.properties");

        properties.load(input);

        dbcp = BasicDataSourceFactory.createDataSource(properties);
        return dbcp;
    }
}

查询操作: QueryRunner()

package rj.dbutils;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.*;
import rj.entity.Student;
import rj.util.DataSourceUtil;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.function.ObjIntConsumer;

public class Test {

    // 只在结果中取一行
    public static void testArrayHandler() throws SQLException {
        // 和连接池建立联系
        QueryRunner runner = new QueryRunner(DataSourceUtil.getDateSourceWithC3P0ByConfig());
        // 执行 SQL 语句,后面的参数是可变的,参数较多时可以用 Object 数组进行传递。
        // new ArrayHandler() 是 ResultSetHandle 的一个实现类,交代我们的返回值类型。
        Object[] student = runner.query("select * from student where sno > ?", new ArrayHandler(), 1);

        System.out.println(student[0] + "," + student[1]);

    }


    // 查询多行信息
    public static void testArrayListHandler() throws SQLException {
        QueryRunner runner = new QueryRunner(DataSourceUtil.getDateSourceWithC3P0ByConfig());

        List<Object[]> student =  runner.query("select * from student where sno > ?", new ArrayListHandler(), 1001);

        for(Object[] s : student) {
            System.out.println(s[0] + "," + s[1]);
        }

    }

    // 拿到一个对象
    public static void testBeanHandler() throws SQLException {
        QueryRunner runner = new QueryRunner(DataSourceUtil.getDateSourceWithC3P0ByConfig());

        Student student = runner.query("select * from student where sno > ?", new BeanHandler<>(Student.class), 1);

        System.out.println(student.getSno()+","+ student.getSname());

    }

    // 放到多个对象中
    public static void testBeanListHandler() throws SQLException {
        QueryRunner runner = new QueryRunner(DataSourceUtil.getDateSourceWithC3P0ByConfig());

        List<Student> students = runner.query("select * from student where sno > ?", new BeanListHandler<>(Student.class), 1);

        for(Student student : students) {
            System.out.println(student.getSno()+","+ student.getSname());

        }

    }


    public static void testBeanMapHandler() throws SQLException {
        QueryRunner runner = new QueryRunner(DataSourceUtil.getDateSourceWithC3P0ByConfig());

        Map<Integer,Student> students =runner.query("select * from student where sno > ?", new BeanMapHandler<Integer,Student>(Student.class,"sno"), 1);

        Student student = students.get(1002);
        System.out.println(student.getSno() + "," + student.getSname());
    }


    // 查询结果集中某一列 ColumnListHandler:  把结果集中某一列,保存到 List 中

    public static void testColumnListHandler() throws SQLException {
        QueryRunner runner = new QueryRunner(DataSourceUtil.getDateSourceWithC3P0ByConfig());

        List<String> names =runner.query("select * from student where sno > ?", new ColumnListHandler<String>("sname"),1);

        for(String name : names) {
            System.out.println(name);

        }

    }

    // long 可以, Integer 不 OK
    public static void testScalarHandler() throws SQLException {
        QueryRunner runner = new QueryRunner(DataSourceUtil.getDateSourceWithC3P0ByConfig());

        Long result = runner.query("select count(*) from student where sno > ?", new ScalarHandler<Long>(),1);

        System.out.println(result);
    }


    public static void main(String[] args) throws SQLException {
//        testArrayHandler();
//        testArrayListHandler();
//        testBeanHandler();
//        testBeanListHandler();
//        testBeanMapHandler();
//        testColumnListHandler();
        testScalarHandler();
    }



}

update操作(增删改):

package rj.dbutils;

import org.apache.commons.dbutils.QueryRunner;
import rj.util.DataSourceUtil;

import java.sql.SQLException;

public class UpdateDemo {

    public static void add() throws SQLException {
        QueryRunner runner = new QueryRunner(DataSourceUtil.getDateSourceWithC3P0ByConfig());

        int result = runner.update("insert into student(sno,sname) value(?,?)", new Object[]{102, "李四"});

        System.out.println(result);
    }

    public static void delete() throws SQLException {
        QueryRunner runner = new QueryRunner(DataSourceUtil.getDateSourceWithC3P0ByConfig());

        int result = runner.update("delete from student where sno = ?",1002);

        System.out.println(result);
    }

    public static void update() throws SQLException {
        QueryRunner runner = new QueryRunner(DataSourceUtil.getDateSourceWithC3P0ByConfig());

        int result = runner.update("update student set sname =? where sno =?",new Object[]{"笨笨",102});

        System.out.println(result);
    }

    public static void main(String[] args) throws SQLException {
//        add();
//        delete();
        update();
    }


}

参考链接:https://www.cnblogs.com/CQY1183344265/p/5854418.html

你可能感兴趣的:(Mysql,JavaWeb)