由于JDBC的使用比较复杂, Apache组织提供了DbUtils, DbUtils是一个对JDBC进行简单封装的开源工具类库,使用它能够 简化JDBC应用程序的开发,同时也不会影响程序的性能。
DBUtils的三个核心功能:
- QueryRunner:提供对sql语句操作的API
- ResultSetHandler接口:用于定义select操作后,如何封装结果集
- DBUtils类,它就是一个工具类,定义了关闭资源与事务处理的方法
QueryRunner
主要介绍以下两种方法:
- query(SQL中 SELECT 语句)
例子: - update(SQL中 INSERT, UPDATE, 或 DELETE 语句)
query
翻看QueryRunner类的源码:
public <T> T query(String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException {
Connection conn = this.prepareConnection();
return this.query(conn, true, sql, rsh, params);
}
public <T> T query(String sql, ResultSetHandler<T> rsh) throws SQLException {
Connection conn = this.prepareConnection();
return this.query(conn, true, sql, rsh, (Object[])null);
}
方法参数如下:
- 用于查询的sql语句
- 用于定义select操作后,封装结果集的接口
- 如果是通过id或其他查询,则需要第三个参数
举例:
// 通过ID查询
public Account findById(Integer accountId) {
try {
return runner.query("select * from account where id=?",new BeanHandler<Account>(Account.class),accountId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
这里解释以下第二个参数new BeanHandler(Account.class):
这个参数对应的是源码中的 ResultSetHandle<T> rsh
rsh参数:ResultSetHandler类型,一般都是创建一个该类型的子类对象然后传进去,该类型有五个常用子类,传递的子类对象会决定query这个方法的返回值。
五个常用子类对象,以及相应的返回值分别是:
- BeanHandler:一个JavaBean对象
- BeanListHandler:一个装有多个JavaBean对象的List集合对象
- MapHandler:一个装有一行结果集的Map对象
- MapListHandler:一个装有多个一行结果集的Map的List集合对象
- ScalarHandler:一个Object类型
update
可用作更新,保存,删除
翻看QueryRunner类的源码:
public int update(String sql) throws SQLException {
Connection conn = this.prepareConnection();
return this.update(conn, true, sql, (Object[])null);
}
public int update(String sql, Object param) throws SQLException {
Connection conn = this.prepareConnection();
return this.update(conn, true, sql, param);
}
举例:
/**
* 保存
* @param account
*/
@Override
public void save(Account account) {
try {
runner.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 更新
* @param account
*/
@Override
public void update(Account account) {
try {
runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 删除
* @param accountId
*/
@Override
public void delete(Integer accountId) {
try {
runner.update("delete from account where id=?",accountId);
} catch (SQLException e) {
e.printStackTrace();
}
}
本文深入解析DbUtils工具库及其核心组件QueryRunner的使用方法,包括SQL查询与更新操作,展示了如何简化JDBC应用程序的开发过程。

被折叠的 条评论
为什么被折叠?



