JDBC开源框架:DBUtils使用入门
在单元测试过程中,只涉及到数据库的直接操作来验证业务逻辑是否正确的情况,DBUtils非常适合使用。它结构简单,包小,友好处理掉那些jdbc异常,让你更专注于业务代码,而非底层的操作。官网对它的定义:Commons DbUtils库是一组小的类,旨在简化JDBC的工作。JDBC资源清理代码是普通的、容易出错的工作,因此这些类从您的代码中抽象出所有清理任务,从而使您真正想要做的事情是:查询和更新数据。
maven
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.7</version>
</dependency>
此是一个非常简洁的工具包,核心二个部分:
1、*Runner 数据库连接操作类,比如增删改查
2、*Handler 结果返回转换类,默认提供常用的转换接口,如基本类型的转换DoubleColumnHandler、LongColumnHandler等。只实现ResultSetHandler接口就可以自定义转换器。
简单说下常用的API
QueryRunner : 此类能够使SQL查询简单化,也支持批量增删改查功能。执行完成后,会自动关闭所有连接,因些不需要手动再次写finally close。
ResultSetHandler : 只有一个简单的接口方法T handle(ResultSet rs)。能将数据转换成想要的任何形式,可以让应用更加简洁操作。默认提供了ArrayHandler, ArrayListHandler, BeanHandler, BeanListHandler, MapHandler, MapListHandler, and ScalarHandler等执行程序。
ColumnHandler : 接口定义让行数据转换。时间类型只实现java.sql.Timestamp的TimestampColumnHandler,在实际项目中,LocalDateTime类型都必需要自定义。
接下来看下具体使用步骤
1、加载jdbc驱动类,获取数据库connection
2、实例化QueryRunner 获得实例化对象queryRunner
3、实现ResultSetHandler,自定义需要转换的数据形式
4、利用queryRunner执行相关DB操作。
例子暂未使用连接池。
public class Member {
private int id;
private String account;
}
public Connection getConn() {
Connection conn = null;
try {
Class.forName(driverName);
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
一、执行增加insert语句有二种方式
1、用QueryRunner.insert()
@Test
public void insert_1() throws Exception {
QueryRunner runner = new QueryRunner();
String sql = "insert into member(account) value('sa')";
MapHandler rsh = new MapHandler();
Map<String, Object> map = runner.insert(getConn(), sql, rsh);
}
返回Map<String,Object> 是自增主键的值,格式:{"GENERATED_KEY":3}
2、用QueryRunner.update();
@Test
public void insert_2() throws Exception {
QueryRunner runner = new QueryRunner();
String sql = "insert into member(account) value('admin')";
int effect = runner.update(getConn(), sql);
}
返回影响的行数。
二、修改update、删除也是一种修改操作
@Test
public void update() throws SQLException {
QueryRunner runner = new QueryRunner();
String sql = "update member set account = ? where id = ?";
Object[] param = {"tom",3};
int effect = runner.update(getConn(), sql, param);
//返回影响的行数
}
@Test
public void delete() throws SQLException {
QueryRunner runner = new QueryRunner();
String sql = "delete from member where id = ?";
int effect = runner.update(getConn(), sql, 2);
//返回影响的行数
}
三、复杂的query,简单列举9种内置常见的handler
1、统计分组类。ScalarHandler 通常用于保存只有一行一列的结果集,例如分组函数
@Test
public void count() throws SQLException {
QueryRunner queryRunner = new QueryRunner();
String sql = "select count(*) cnt from member";
long count = (long) queryRunner.query(getConn(), sql, new ScalarHandler()); // 默认得到结果集的第1列
long cnt = (long) queryRunner.query(getConn(), sql, new ScalarHandler("cnt")); //使用定义的别名
}
2、KeyedHandler 将结果集每一行数据保存到一个Map。里面map,key为列名,value为值;外面的map,key为指定列名的值,value对应的那条数据,即里面map
@Test
public void keyedhandler() throws SQLException {
QueryRunner queryRunner = new QueryRunner();
String sql = "select * from member";
Map<Object, Map<String, Object>> map = (Map<Object, Map<String, Object>>) queryRunner.query(getConn(), sql, new KeyedHandler<Object>("id"));
System.out.println(JSON.toJSONString(map));
}
3、MapListHandler 将结果集每一行数据保存到map中,key列名 value该列的值 ---- 再将所有map对象保存到List集合中
@Test
public void mapListQuery() throws SQLException {
QueryRunner queryRunner = new QueryRunner();
String sql = "select * from member";
MapListHandler map = new MapListHandler();
List<Map<String, Object>> list = queryRunner.query(getConn(), sql, map);
}
4、 MapHander 将结果集第一行数据封装到Map集合中,key是列名,value为该列的值
@Test
public void mapQuery() throws SQLException {
QueryRunner queryRunner = new QueryRunner();
String sql = "select * from member";
MapHandler map = new MapHandler();
Map<String, Object> m = queryRunner.query(getConn(), sql, map);
}
5、 ColumnListHandler 获得结果集的某一列,将该列的所有值存入List<Object>中。可以传columnIndex和columnName二参数,默认取第一列的值
@Test
public void columnListQuery() throws SQLException {
QueryRunner queryRunner = new QueryRunner();
String sql = "select * from member";
ColumnListHandler<String> listHandler = new ColumnListHandler("id");
List<String> list = queryRunner.query(getConn(), sql, listHandler);
System.out.println(JSON.toJSONString(list));
}
6、BeanListHander 将结果集每一条数据,转为JavaBean对象,再保存到list集合中
@Test
public void beanListQuery() throws SQLException {
QueryRunner queryRunner = new QueryRunner();
String sql = "select * from member";
BeanListHandler<Member> listHandler = new BeanListHandler(Member.class);
List<Member> list = queryRunner.query(getConn(), sql, listHandler);
System.out.println(JSON.toJSONString(list));
}
7、 BeanHandler 将结果集第一行数据封装到JavaBean对象中,与MapHandler意思一样
@Test
public void beanQuery() throws SQLException {
QueryRunner queryRunner = new QueryRunner();
String sql = "select * from member";
BeanHandler<Member> listHandler = new BeanHandler(Member.class);
Member member = queryRunner.query(getConn(), sql, listHandler);
System.out.println(JSON.toJSONString(member));
}
8、 ArrayListHandler 将结果集每一行数据保存到List<Object[]>中
@Test
public void arrayListQuery() throws SQLException {
QueryRunner queryRunner = new QueryRunner();
String sql = "select * from member";
ArrayListHandler listHandler = new ArrayListHandler();
List<Object[]> list = queryRunner.query(getConn(), sql, listHandler);
System.out.println(JSON.toJSONString(list));
}
9、 ArrayHandler 将结果集第一行数据保存到Object[]中
@Test
public void arrayQuery() throws SQLException {
QueryRunner queryRunner = new QueryRunner();
String sql = "select * from member";
ArrayHandler listHandler = new ArrayHandler();
Object[] list = queryRunner.query(getConn(), sql, listHandler);
System.out.println(JSON.toJSONString(list));
}