【重点】commons-dbutils

DBUtils

简介

DBUtils是Java编程中的数据库操作实用工具,小巧简单实用。DBUtils封装了对JDBC的操作,简化了JDBC操作,可以减少60%以上的代码。

DBUtils三个核心功能介绍

  • QueryRunner:核心类提供对sql语句操作的API
    • QueryRunner(DataSourcr ds):提供数据源(连接池),DbUtils底层自动维护连接connection
    • update(String sql,Obj…params):执行更新操作
    • query(String sql,ResultSetHandlerrsh,Object…panrams):执行查询操作
  • ResultSetHandler:结果集处理类,用于定义select操作后,怎样封装结果集
    • ArrayHandler:把查询结果集中的第一行数据放到一个数组中。适合取1条记录。
    • ArrayListHandler:将查询的结果的每一行数据都放到一个数组中,然后再将数组放到集合List中。适合取多条记录。
    • BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中
    • BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,然后再将这些对象存放到List里。
    • MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
    • MapListHandler:将查询的结果的每一行存入到一个map中,键为列名,值为各列值;然后再将map存入list中
    • ColumnListHandler:将结果集中某一列的数据存放到List中。
    • KeyedHandler(name):将结果集中的每一行数据都封装到一个Map里(List),再把这些map再存到一个map里,其key为指定的列。
    • ScalarHandler:将结果集第一行的某一列放到某个对象中。//重点
  • DBUtils:工具类,定义了关闭资源与事务处理的方法。

示例:采用Druid和dbutils实现对Dept的CRUD

  • 第一步:Dept.java:Dept源代码

  • 第二步:新建项目,加入Maven依赖:

    <dependency>
      <groupId>commons-dbutils</groupId>
      <artifactId>commons-dbutils</artifactId>
      <version>1.7</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.17</version>
    </dependency>
    
  • 第二步:在resources目录下创建mysql.properties,代码如下:

    driverClassName=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&user=root&password=&useUnicode=true&characterEncoding=UTF8&autoReconnect=true&failOverReadOnly=false
    username=root
    password=root
    
    filters=stat
    initialSize=2
    maxActive=300
    maxWait=60000
    timeBetweenEvictionRunsMillis=60000
    minEvictableIdleTimeMillis=300000
    validationQuery=SELECT 1
    testWhileIdle=true
    testOnBorrow=false
    testOnReturn=false
    poolPreparedStatements=false
    maxPoolPreparedStatementPerConnectionSize=200
    
  • 第三步:创建数据库连接工具类:

    public class DBUtil {
        private static DataSource dataSource = null;
    
        private DBUtil() {
        }
        public static DataSource getDataSource(){
        	return this.dataSource;
        }
    
        static {    //配置文件加载,只执行一次
            try (InputStream is = DBUtil.class.getResourceAsStream("/mysql.properties");) {
                Properties properties = new Properties();
                properties.load(is);
                dataSource = DruidDataSourceFactory.createDataSource(properties);
            } catch (Exception e1) {
                throw new RuntimeException("读取配置文件异常", e1);
            }
        }
    
        public static void release(Connection conn, Statement stmt, ResultSet rs) {
            DbUtils.closeQuietly(conn);
            DbUtils.closeQuietly(stmt);
            DbUtils.closeQuietly(rs);
        }
    }
    
  • 第四步:测试事务(重点)

    public static void main(String[] args) {
        Connection conn = null;
        try {
            //获取连接池
            DataSource dataSource = DBUtil.getDataSource();
            QueryRunner queryRunner = new QueryRunner(dataSource);
            //获取连接,用来控制事务
            conn = dataSource.getConnection();
            
            conn.setAutoCommit(false); // 设置事务提交为手动
            
            String sql = "insert into tb_dept (dname,loc) values(?,?)";
            queryRunner.update(conn, sql, "aa", "aaaaa");
            System.out.println(3 / 0);
            queryRunner.update(sql, "bb", "bbbbbbbbbb");
            //提交事务
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                if(conn !=null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
             try {
                if (conn != null) {
                    //恢复事务
                    conn.setAutoCommit(true);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • 第五步:DeptDaoImpl.java

    public class DeptDaoImpl {
    	//返回数据库中受影响的记录的行数
        public int insertDept1(Dept dept) throws SQLException {
            QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
            String sql = "insert into tb_dept (deptno, dname, loc) values (?, ?, ?)";
            int res = queryRunner.update(sql, dept.getDeptno(), dept.getDname(), dept.getLoc());
            return res;
        }
    
        public int batchInsertDept(List<Dept> deptList) throws SQLException {
            Object[][] params = new Object[deptList.size()][3];
    
            for (int i = 0; i < params.length; i++) {
                Dept dept = deptList.get(i);
                params[i][0] = dept.getDeptno();
                params[i][1] = dept.getDname();
                params[i][2] = dept.getLoc();
            }
    
            StringBuilder wenHao = new StringBuilder();
            for (int i = 0; i < params[0].length; i++) {
                wenHao.append("?,");
            }
            String sql = "insert into tb_dept values(" + wenHao.deleteCharAt(wenHao.length() - 1) + ")";
    	   
    	    QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
            queryRunner.batch(sql, params);
            return 1;  // 如果不抛出异常,就返回1,表示删除成功
        }
    
        public int deleteDeptByDeptno(Byte deptno) throws SQLException {
        	QueryRunner queryRunner = new QueryRunner(dataSource);
            String sql = "delete from tb_dept where deptno = ?";
            return queryRunner.update(sql, deptno);
        }
    
        public int deleteDeptByCondition(Dept dept) throws SQLException {
            List<Object> paramValueList = new ArrayList<>();
            StringBuffer paramBuf = new StringBuffer("1=1 ");
    
            if (dept.getDeptno() != null) {
                paramBuf.append("and deptno= ? ");
                paramValueList.add(dept.getDeptno());
            }
            if (dept.getDname() != null) {
                paramBuf.append("and dname= ? ");
                paramValueList.add(dept.getDname());
            }
            if (dept.getLoc() != null) {
                paramBuf.append("and loc= ? ");
                paramValueList.add(dept.getLoc());
            }
    
            String sql = "delete from tb_dept where " + paramBuf.substring(0, paramBuf.length() - 3);
            
            QueryRunner queryRunner = new QueryRunner(dataSource);
            return queryRunner.update(sql, paramValueList.toArray());
        }
    
        public int batchDeleteDeptByDeptnos(String deptnos) throws SQLException {
            String[] split = deptnos.split(",");
            Object[][] params = new Object[1][];
    
            StringBuilder wenHao = new StringBuilder();
            for (int i = 0; i < split.length; i++) {
                wenHao.append("?,");
            }
            params[0] = split;
    
            String sql = "delete from tb_dept where deptno in (" + wenHao.deleteCharAt(wenHao.length() - 1) + ")";
    	    
    	    QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
            queryRunner.batch(sql, params);
            return 1;  // 如果不抛出异常,就返回1,表示删除成功
        }
    
        public int updateDept(Dept dept) throws SQLException {
        	QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
            String sql = "update tb_dept set dname= ? ,loc= ? where deptno = ?";
            return queryRunner.update(sql, dept.getDname(), dept.getLoc(), dept.getDeptno());
        }
    
        public long selectCount() throws SQLException {
        	QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
            String sql = "select count(*) from tb_dept";
            // ScalarHandler:将查询的结果的第一行的某一列放到一个对象中;精确定位到某个值
            Long query = queryRunner.query(sql, new ScalarHandler<Long>());
            return query.intValue();
        }
    
        public long selectCountByCondition(Dept dept) throws SQLException {
            List<Object> paramValueList = new ArrayList<>();
            StringBuffer paramBuf = new StringBuffer("1=1 ");
    
            if (dept.getDeptno() != null) {
                paramBuf.append("and deptno= ? ");
                paramValueList.add(dept.getDeptno());
            }
            if (dept.getDname() != null) {
                paramBuf.append("and dname= ? ");
                paramValueList.add(dept.getDname());
            }
            if (dept.getLoc() != null) {
                paramBuf.append("and loc= ? ");
                paramValueList.add(dept.getLoc());
            }
    
            String sql = "select count(*) from tb_dept where " + paramBuf.substring(0, paramBuf.length() - 3);
            
            QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
            Long query = queryRunner.query(sql, new ScalarHandler<Long>(), paramValueList.toArray());
            return query.intValue();
        }
    
        public Dept selectDeptByDeptno(Byte deptno) throws SQLException {
            String sql = "select deptno as deptno, dname as dname, loc as loc from tb_dept where  deptno = ?";
            QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
            return queryRunner.query(sql, new BeanHandler<>(Dept.class), deptno);
        }
    
        public List<Dept> selectAllDept() throws SQLException {
            String sql = "select deptno as deptno, dname as dname, loc as loc from tb_dept";
            
            QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
            return queryRunner.query(sql, new BeanListHandler<>(Dept.class));
        }
    
        public List<Dept> selectDeptByCondition(Dept dept) throws SQLException {
            List<Object> paramValueList = new ArrayList<>();
            StringBuffer paramBuf = new StringBuffer("1=1 ");
    
            if (dept.getDeptno() != null) {
                paramBuf.append("and deptno= ? ");
                paramValueList.add(dept.getDeptno());
            }
            if (dept.getDname() != null) {
                paramBuf.append("and dname= ? ");
                paramValueList.add(dept.getDname());
            }
            if (dept.getLoc() != null) {
                paramBuf.append("and loc= ? ");
                paramValueList.add(dept.getLoc());
            }
    
            String sql = "select deptno as deptno, dname as dname, loc as loc  from tb_dept where " + paramBuf.substring(0, paramBuf.length() - 3);
            
            QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
            return queryRunner.query(sql, new BeanListHandler<>(Dept.class), paramValueList.toArray());
        }
    
        public List<Dept> selectDeptWithPagination(int page, int rows) throws SQLException {
        	QueryRunner queryRunner = new QueryRunner(dataSource);
            String sql = "select deptno as deptno, dname as dname, loc as loc from tb_dept limit ?, ?";
            return queryRunner.query(sql, new BeanListHandler<>(Dept.class), (page - 1) * rows, rows);
        }
    
        public List<Dept> selectDeptWithPaginationByCondition(int page, int rows, Dept dept) throws SQLException {
            List<Object> paramValueList = new ArrayList<>();
            StringBuffer paramBuf = new StringBuffer("1=1 ");
    
            if (dept.getDeptno() != null) {
                paramBuf.append("and deptno= ? ");
                paramValueList.add(dept.getDeptno());
            }
            if (dept.getDname() != null) {
                paramBuf.append("and dname= ? ");
                paramValueList.add(dept.getDname());
            }
            if (dept.getLoc() != null) {
                paramBuf.append("and loc= ? ");
                paramValueList.add(dept.getLoc());
            }
    
            String sql = "select deptno as deptno, dname as dname, loc as loc  from tb_dept where " + paramBuf.substring(0, paramBuf.length() - 3) + " limit ?, ?";
    
            paramValueList.add((page - 1) * rows);
            paramValueList.add(rows);
            
            QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
            return queryRunner.query(sql, new BeanListHandler<>(Dept.class), paramValueList.toArray());
        }
    }
    
commons-dbutils包是Apache开源组织提供的用于操作数据库的工具包。简单来讲,这个工具包就是用来更加方便我们操作数据库的,最近工作中使用了一下,感觉确实方便很多,基本告别自己封装JDBC代码对数据库进行增删改查了。代码看着也很简洁。 例如: 增删改查使用的类:QueryRunner类+ResultSetHandler类,使用这俩类就可以解决掉。 QueryRunner类的query()方法:new QueryRunner().query(Connection conn, String sql, ResultSetHandler rsh) query方法后面参数中加一个Connection连接,是在获取不到数据源的情况下,也就是说,QueryRunner的实例化构造函数使用无参的那个,下面我的实现代码就是用的这种方法。 当然还有一种实例化:new QueryRunner(new Datasource()).query(String sql, ResultSetHandler rsh) query方法中的参数 ResultSetHandler 参数中加上ResultSetHandler接口的实现类参数(下面这些实现类),执行完SQL后,返回的数据就是已经封装好的我们想要的结果了。 ArrayHandler :将ResultSet中第一行的数据转化成对象数组 ArrayListHandler将ResultSet中所有的数据转化成List,List中存放的是Object[] BeanHandler :将ResultSet中第一行的数据转化成Bean对象 BeanListHandler :将ResultSet中所有的数据转化成List ColumnListHandler :将ResultSet中某一列的数据存成List KeyedHandler :将ResultSet中存成映射,key为某一列对应为Map,Map中存放的是数据 MapHandler :将ResultSet中第一行的数据存成Map MapListHandler :将ResultSet中所有的数据存成List<Map> ScalarHandler :将ResultSet中一条记录的其中某一列的数据存成Object
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梁云亮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值