Apache-DBUtils常用类介绍

介绍

commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。使用该工具之前先导入commons-dbutils-1.4.jar

常用类及方法

QuerryRunner类

核心运行类, 提供对sql语句操作的方法

构造: QueryRunner(DataSource ds);
普通方法: int update(String sql,Object… args); //用来完成表数据的增加、删除、更新操作
T query(String sql,ResultSetHandler rsh,Object… args);//用来完成表数据的查询操作

ResultSetHandler接口

SQL结果集接口
ResultSetHandler接口实现类关系图如下:
这里写图片描述

DbUtils.commitAndCloseQuietly(conn)

提交事物并安静的释放资源

DbUtils.rollback(conn)

事务回滚

示例

1.带有事务的转账功能。该案例需要依赖c3p0jar包且有c3p0-config.xml配置文件,配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/web_test4</property>
        <property name="user">root</property>
        <property name="password">123456</property>
    </default-config>
</c3p0-config>
@Test
public void accoutnTransaction(){
    Connection conn = null;
    QueryRunner queryRunner = null;
    try {
        // 1.获得连接
        conn = C3P0Utils.getConnection();
        // 2.创建关键类
        queryRunner = new QueryRunner();
        // 3.开启事务
        conn.setAutoCommit(false);
        // 4.执行sql
        queryRunner.update(conn, "UPDATE account SET money = money + ? WHERE id = ?", -1000, 1);
        queryRunner.update(conn, "UPDATE account SET money = money + ? WHERE id = ?", +1000, 2);
        // 5.提交事务
        DbUtils.commitAndCloseQuietly(conn);
        System.out.println("转账成功");
    } catch (Exception e) {
        // TODO Auto-generated catch block
        try {
            DbUtils.rollback(conn);
        } catch (SQLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        System.out.println("转账失败");
        e.printStackTrace();
    }
}

2.QueryRunner的query方法介绍
使用BeanListHandler类接收结果集最常见

带有筛选条件
public void beanSelectAccount() throws SQLException{
    // 关键类QueryRunner/BeanListHandler
    QueryRunner queryRunner = new QueryRunner(C3P0Utils.getComboPooledDataSource());
    List<Account> list = queryRunner.query("SELECT * FROM account WHERE id > ?", new BeanListHandler<Account>(Account.class), 3);
    for(Account account : list){
        System.out.println(account);
    }
}
不带筛选条件
public void beanSelectAccount() throws SQLException{
        // 关键类QueryRunner/BeanListHandler
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getComboPooledDataSource());
        List<Account> list = queryRunner.query("SELECT * FROM account WHERE id", new BeanListHandler<Account>(Account.class));
        for(Account account : list){
            System.out.println(account);
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_27252133/article/details/79818460
今日推荐