DbUtils:JDBC实用组件实例

这一页提供了一些展示如何使用DbUtils的示例。

基本用法

DbUtils是一个非常小的类库,因此浏览完所有类的javadoc不会花费很长时间。DbUtils的核心类/接口是QueryRunnerResultSetHandler。你不需要知道其它DbUtils类就可以使用这一类库。下面的例子展示了这些类是如何一起使用的。

// Create a ResultSetHandler implementation to convert the
// first row into an Object[].
// 创建一个ResultSetHandler 实现,以把第一行转换成一个Object[]
ResultSetHandler<Object[]> h = new ResultSetHandler<Object[]>() {
public Object[] handle(ResultSet rs) throws SQLException {
if (!rs.next()) {
return null;
} ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
Object[] result = new Object[cols]; for (int i = 0; i < cols; i++) {
result[i] = rs.getObject(i + 1);
} return result;
}
}; // Create a QueryRunner that will use connections from
// the given DataSource
// 创建一个QueryRunner,它会使用所给DataSource的连接
QueryRunner run = new QueryRunner(dataSource); // Execute the query and get the results back from the handler
// 执行查询并从handler获取结果
Object[] result = run.query(
"SELECT * FROM Person WHERE name=?", h, "John Doe");

  

 

你也可以通过 java.sql.Connection 对象来代替 DataSource来执行先前的操作。注意,在这个例子中,你应该负责关闭Connection 。

 
ResultSetHandler<Object[]> h = ... // Define a handler the same as above example
// 定义一个和上面例子一样的handler // No DataSource so we must handle Connections manually
// 没有DataSource,所以我们必须手动处理Connections
QueryRunner run = new QueryRunner(); Connection conn = ... // open a connection // 打开一个连接
try{
Object[] result = run.query(conn, "SELECT * FROM Person WHERE name=?", h, "John Doe");
// do something with the result
// 用result做些什么吧~
} finally {
// Use this helper method so we don't have to check for null
// 使用DbUtils的方法,所以我们不需要检查是否为null
DbUtils.close(conn);
}

  

你不仅可以从数据库获取数据,你也可以插入或者更新数据。下面的例子将首先插入一个person到数据库,并且之后改变person的height属性。

QueryRunner run = new QueryRunner( dataSource );
try
{
// Execute the SQL update statement and return the number of
// inserts that were made
// 执行SQL更新语句,并返回插入的数量???
int inserts = run.update( "INSERT INTO Person (name,height) VALUES (?,?)", "John Doe", 1.82 );
// The line before uses varargs and autoboxing to simplify the code
// 上一行使用可变参数和自动装箱以简化代码 // Now it's time to rise to the occation...
// 现在是时候进入正题了
int updates = run.update( "UPDATE Person SET height=? WHERE name=?", 2.05, "John Doe" );
// So does the line above
// 正如上一行所做
}
catch(SQLException sqle) {
// Handle it
// 处理它
}

  

对于长时间运行的调用,你可以使用 AsyncQueryRunner异步执行调用。 AsyncQueryRunner 类和 QueryRunner 类调用具有相同的方法;然而,这些方法返回一个Callable.

ExecutorCompletionService<Integer> executor = new ExecutorCompletionService<Integer>( Executors.newCachedThreadPool() );
AsyncQueryRunner asyncRun = new AsyncQueryRunner( dataSource ); try
{
// Create a Callable for the update call
// 为update调用创建一个Callable对象
Callable<Integer> callable = asyncRun.update( "UPDATE Person SET height=? WHERE name=?", 2.05, "John Doe" );
// Submit the Callable to the executor
// 向executor提交Callable对象
executor.submit( callable );
} catch(SQLException sqle) {
// Handle it
// 处理它
} // Sometime later (or in another thread)
// 稍后(或在另一个线程之中)
try
{
// Get the result of the update
// 获取update的结果
Integer updates = executor.take().get();
} catch(InterruptedException ie) {
// Handle it
// 处理异常
}

  

ResultSetHandler的实现

在上面的例子中,我们实现了 ResultSetHandler 接口以把 ResultSet 第一行数据转换成一个Object[]。这是一个相当通用的实现,它可以在很多项目中重用。为了认识到这一点,DbUtils在org.apache.commons.dbutils.handlers包中提供了一系列 ResultSetHandler 实现,这些实现可以执行通常转换成array,maps,和JavaBean。There is a version of each implementation that converts just the first row and another that converts all rows in the ResultSet.下面是每一个实现的一个版本,这些都只是把第一行转换了,以及转换了在 ResultSet中的所有行。

我们将以一个例子开始,使用 BeanHandler 从 ResultSet 获取一行并把它转换成一个JavaBean。

QueryRunner run = new QueryRunner(dataSource);

// Use the BeanHandler implementation to convert the first
// ResultSet row into a Person JavaBean.
// 使用BeanHandler实现以把ResultSet中第一行转换成一个Person JavaBean
ResultSetHandler<Person> h = new BeanHandler<Person>(Person.class); // Execute the SQL statement with one replacement parameter and
// return the results in a new Person object generated by the BeanHandler.
// 执行有一个替代参数的SQL语句,并把返回结果存入由BeanHandler生成的Person对象
Person p = run.query("SELECT * FROM Person WHERE name=?", h, "John Doe");

  

现在我们将使用BeanListHandler从 ResultSet获取所有行,并以JavaBean List 的形式返回。

QueryRunner run = new QueryRunner(dataSource);

// Use the BeanHandler implementation to convert the first
// ResultSet row into a Person JavaBean.
// 使用BeanListHandler实现以把所有的结果集行转换成Person JavaBean列表
ResultSetHandler<List<Person>> h = new BeanListHandler<Person>(Person.class); // Execute the SQL statement and return the results in a List of
// Person objects generated by the BeanListHandler.
// 执行SQL语句并返回由BeanListHandler生成的Person对象列表
List<Person> persons = run.query("SELECT * FROM Person", h);

  

自定义RowProcessor

每一个所提供的ResultSetHandler 实现接收一个RowProcessor 来做真实的行到对象的转换。通过默认处理器使用BasicRowProcessor 实现,但是你可以实现一个自定义的版本来插入。可能最通用的自定义是去实现toBean() 方法来处理自定义数据库数据类型问题。

自定义BeanProecssor

BasicRowProcessor 使用一个BeanProcessor 来把 ResultSet 列转成JavaBean 属性. 你可以子类化并覆盖处理流程来指定你的应用程序的数据类型映射。所提供的实现把数据类型转换委托给JDBC驱动。

BeanProcessor 把列映射成为bean属性,如在BeanProcessor.toBean() Java文档中所述。 列名必须匹配bean的属性名,且区分大小写。例如,通过调用 setFirstName() 方法,firstname 类可以存储在bean中。然而,很多数据库列明包含或者不能使用或者在Java方法名中不常用的字符。你可以通过以下两种方法之一以把bean属性映射到这些列中。

  1. 把SQL中的列名别名化以使它们和Java属性名匹配: select social_sec# as socialSecurityNumber from person
  2. 子类化BeanProcessor,并覆盖方法mapColumnsToProperties() 来删除违规字符。

原文

  原文传送门

最新文章

  1. GIT和SVN之间的区别及基本操作对比
  2. Redis和Memcached整体
  3. C/C++编程语言学习资料尽收眼底 电子书+视频教程
  4. 2013长沙赛区现场赛 J - Josephina and RPG
  5. Checkpoint--与lazy writer区别
  6. 【cl】Json学习
  7. To do
  8. 反射认识_04_反射调用类方法Method
  9. hdu 1061 Rightmost Digit
  10. POJ 2159 Ancient Cipher 难度:0
  11. 【转】select和epoll模型的差异
  12. Hibernate一级缓存、二级缓存
  13. Javascript数组方法探究一二
  14. Windows 中默认安装的.Net 版本
  15. firefox 不能显示 glyphicons 字体
  16. ios NSString拼接方法总结
  17. 安卓手机如何快速投屏到windows(10/8.1/7)电脑上
  18. scheduleAtFixedRate 与 scheduleWithFixedDelay 的区别
  19. requestium
  20. web.py框架之高级应用

热门文章

  1. poj 1655 树的重心 &amp;&amp; define注意事项
  2. sublime开启vi编辑器功能,与vi常用快捷键
  3. Spring课程 Spring入门篇 5-2 配置切面aspect
  4. 重构指南 - 移除重复内容(Remove Duplication)
  5. idea tomcat 日志的存放路径
  6. SQLAlchemy的使用---增删改查
  7. Python爬虫《Python网络爬虫相关基础概念》
  8. Web安全色的意义
  9. Android 自定义Dialog中加EditText弹不出键盘跟Dialog遮挡键盘的问题
  10. jQuery判断checkbox是否选中?操作checkbox(不)选中?