Apache-DBUtils实现CRUD
1. Apache-DBUtils简介
-
commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。
-
commons-dbutils下载地址:https://github.com/apache/commons-dbutils
-
API文档地址:https://javadoc.io/doc/commons-dbutils/commons-dbutils/latest/index.html
-
主要API介绍:
-
org.apache.commons.dbutils.DbUtils
此类提供了加载JDBC驱动和一系列关闭资源的静态方法;
-
org.apache.commons.dbutils.QueryRunner
此类提供了操作数据库的一系列重载的update()和query()方法;
-
org.apache.commons.dbutils.ResultSetHandler
此接口用于处理数据库查询得到的结果集,针对不同的结果集采用不同的子类来实现;
-
2. 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 | 允许conn为null,对连接执行回滚,然后将其关闭,如果为空,请避免关闭 |
rollbackAndCloseQuietly(Connection) | 允许conn为null,对连接执行回滚,然后将其关闭,如果为空则避免关闭,并隐藏发生的任何SQLExceptions |
public static boolean loadDriver(java.lang.String driverClassName) | 这一方装载并注册JDBC驱动程序,如果成功就返回true;使用该方法,你不需要捕捉这个异常ClassNotFoundException |
演示关闭资源的代码
public static void closeResourceByDBUtils(Connection conn, PreparedStatement ps, ResultSet rs) {
DbUtils.closeQuietly(conn);
DbUtils.closeQuietly(ps);
DbUtils.closeQuietly(rs);
}
//或者
public static void closeResource(Connection conn, Statement ps, ResultSet rs){
try {
DbUtils.close(conn);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
DbUtils.close(ps);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
DbUtils.close(rs);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
3. QueryRunner类的使用
3.1 主要方法
-
该类简单化了SQL查询,它与ResultSetHandler组合在一起使用可以完成大部分的数据库操作,能够大大减少编码量。
-
QueryRunner类提供了多个构造器,我们常用的主要是:
-
- 默认的空参构造器
- 需要一个 javax.sql.DataSource 来作参数的构造器
-
QueryRunner类的主要方法:
- 执行
- public int execute(Connection conn, String sql, Object… params) throws SQLException:用来执行更新操作,返回更新的行数
- …
- 更新
- 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 的创建和关闭。
- …
- 执行
3.2 执行代码演示:
package com.jdbc.dbutils;
import java.sql.Connection;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;
import com.jdbc.util.JDBCUtils;
public class QueryRunnerTest {
@Test
//测试插入(增删改相似)
public void testInsert() throws Exception {
//1.获取数据库连接
Connection conn = JDBCUtils.getConnectionByDruid();
//2.创建QueryRunner的实例
QueryRunner runner = new QueryRunner();
//3.定义SQL语句
String sql = "insert into customers(name,email,birth)values(?,?,?)";
//4.调用QueryRunner实例的update()方法,返回添加行数
int i = runner.update(conn, sql, "黑桃A","A@qq.com","1980-09-22");
System.out.println("添加了" + i + "条记录");
//5.关闭资源
JDBCUtils.closeResourceCommen(conn, null, null);
}
@Test
//测试删除
public void testDelete() throws Exception {
Connection conn = JDBCUtils.getConnectionByDruid();
QueryRunner runner = new QueryRunner();
String sql = "delete from customers where id < ?";
int i = runner.update(conn,sql,2);
System.out.println("删除了" + i + "条记录");
JDBCUtils.closeResourceCommen(conn, null, null);
}
}
4. ResultSetHandler接口及实现类
4.1 主要实现类
-
该接口用于处理 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:查询单个值对象
-
4.2 代码演示
4.2.1 BeanHandler演示:
/**
* BeanHandler:是ResultedHandler接口的实现类,用于封装表中的一条记录。(不能返回多条记录)
* @throws Exception
*/
@Test
public void testQuery1() throws Exception {
// 1.获取数据库连接
Connection conn = JDBCUtils.getConnectionByDruid();
// 2.创建QueryRunner的实例
QueryRunner runner = new QueryRunner();
// 3.定义sql语句
String sql = "select id,name,email,birth from customers where id = ?";
// 4.创建BeanHandler<>的实例
BeanHandler<Customers> handler = new BeanHandler<>(Customers.class);
// 5.调用runner的query方法
Customers customers = runner.query(conn, sql, handler, 12);
System.out.println(customers);
// 6.关闭资源
JDBCUtils.closeResourceByDBUtils(conn, null, null);
}
4.2.2 BeanListHandler演示:
/**
* BeanListHandler是ResultedHandler接口的实现类,用于封装表中的多条记录构成的集合
* @throws Exception
*/
@Test
public void testQuery2() throws Exception {
// 1.获取数据库的连接
Connection conn = JDBCUtils.getConnectionByDruid();
// 2.创建QueryRunner的实例
QueryRunner runner = new QueryRunner();
// 3.定义sql语句
String sql = "select id,name,email,birth from customers where id < ?";
// 4.创建BeanListHandler的实例
BeanListHandler<Customers> listHandler = new BeanListHandler<>(Customers.class);
// 5.调用runner的query方法
List<Customers> list = runner.query(conn, sql, listHandler, 8);
list.forEach(System.out::println);
// 6.关闭资源
JDBCUtils.closeResourceByDBUtils(conn, null, null);
}
4.2.3 MapHandler演示:
/**
* MapHandler:是ResultedHandler接口的实现类,对应表中的一条记录 将字段及相应字段值作为map中的key和value
* @throws Exception
*/
@Test
public void testQuery3() throws Exception {
Connection conn = JDBCUtils.getConnectionByDruid();
QueryRunner runner = new QueryRunner();
String sql = "select id,name,email,birth from customers where id = ?";
MapHandler handler = new MapHandler();
Map<String, Object> map = runner.query(conn, sql, handler, 12);
System.out.println(map); // 以键值对的方式实现输出
JDBCUtils.closeResourceByDBUtils(conn, null, null);
}
4.2.4 MapListHandler演示:
/**
* MapListHandler:是ResultedHandler接口的实现类,对应表中的多条记录
* 将字段及相应字段值作为map中的key和value,将这些map添加到list中
* @throws Exception
*/
@Test
public void testQuery4() throws Exception {
Connection conn = JDBCUtils.getConnectionByDruid();
QueryRunner runner = new QueryRunner();
String sql = "select id,name,email,birth from customers where id < ?";
MapListHandler listHandler = new MapListHandler();
List<Map<String, Object>> list = runner.query(conn, sql, listHandler, 12);
list.forEach(System.out::println);
JDBCUtils.closeResourceByDBUtils(conn, null, null);
}
4.2.5 ScalarHandler演示:
/**
* ScalarHandler:用于查询特殊值,如查询类似于最大的,最小的,平均的,总和,个数相关的数据
* @throws Exception
*/
@Test
public void testQuery5() throws Exception {
Connection conn = JDBCUtils.getConnectionByDruid();
QueryRunner runner = new QueryRunner();
String sql = "select count(*) from customers"; // 查询customers表中有多少条记录
ScalarHandler handler = new ScalarHandler();
Long count = (Long) runner.query(conn, sql, handler); // 向下转型
System.out.println("customers中有" + count + "条记录");
JDBCUtils.closeResourceByDBUtils(conn, null, null);
}
@Test
public void testQuert6() throws Exception {
Connection conn = JDBCUtils.getConnectionByDruid();
QueryRunner runner = new QueryRunner();
String sql = "select min(birth) from customers";
ScalarHandler handler = new ScalarHandler();
Date minbirth = (Date) runner.query(conn, sql, handler);
System.out.println("出生最早的在" + minbirth);
JDBCUtils.closeResourceByDBUtils(conn, null, null);
}
4.2.6 自定义ResultSetHandler演示:
/**
* --自定义ResultSetHandler的实现类完成查询操作
* @throws Exception
*/
@Test
public void testQuery() throws Exception {
Connection conn = JDBCUtils.getConnectionByDruid();
QueryRunner runner = new QueryRunner();
String sql = "select * from customers where id = ?"; // 不建议使用 * 来选取表列
ResultSetHandler<Customers> handler = new ResultSetHandler<Customers>() {
@Override
public Customers handle(ResultSet rs) throws SQLException {
if (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
Date birth = rs.getDate("birth");
Customers customers = new Customers(id, name, email, birth);
return customers;
}
return null;
}
};
Customers customers = runner.query(conn, sql, handler, 7);
System.out.println(customers);
JDBCUtils.closeResourceByDBUtils(conn, null, null);
}