DbUtils: JDBC Utility Component Examples翻译
DbUtils:JDBC实用组件实例
这一页提供了一些展示如何使用DbUtils的示例。
基本用法
DbUtils是一个非常小的类库,因此浏览完所有类的javadoc不会花费很长时间。DbUtils的核心类/接口是QueryRunner和ResultSetHandler。你不需要知道其它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属性映射到这些列中。
- 把SQL中的列名别名化以使它们和Java属性名匹配: select social_sec# as socialSecurityNumber from person
- 子类化BeanProcessor,并覆盖方法mapColumnsToProperties() 来删除违规字符。
原文
DbUtils: JDBC Utility Component Examples翻译的更多相关文章
- DbUtils: JDBC Utility Component Examples
DbUtils: JDBC Utility Component Examples \JDBCCollector\jdbc\src\main\java\com\ai\toptea\collection\ ...
- Apache DbUtils - JDBC轻量级封装的工具包
前段时间使用了Apache Common DbUtils这个工具,在此留个印,以备不时查看.大家都知道现在市面上的数据库访问层的框架很多,当然很多都是包含了OR-Mapping工作步骤的例如大家常用的 ...
- DbUtils使用例子
DbUtils: JDBC Utility Component Examples This page provides examples that show how DbUtils may be us ...
- jdbc ---- DBUTilDao 类
1, 列用工具包 阿里的 DbUtils: JDBC Utility Component Examples 再次封装成通用的 update, query package com.ljs.dao; i ...
- 【JavaWeb】DbUtils入门之QueryRunner
DbUtils简介 根据官网的介绍,DbUtils是一种 JDBC Utility Component (翻译过来大概就是:JDBC实用部件),故名思意,和数据库操作有关 官网上的简介也称之为 JDB ...
- JDBC + MySQL 示例
jdbc mysql connection 教程 翻译自:JDBC MySQL Connection Tutorial Java Database Connectivity (JDBC) 是一个基于J ...
- JDBC 基础知识总结
1. 何谓JDBC --- Java Database Connectivity. 由Sun 公司提供的访问数据库的一组java类和接口,用来对数据库进行链接.发送SQL语句.处理返回结果,为开发 ...
- JDBC处理大数据
1.处理大文本 package com.demo; import java.io.File; import java.io.FileNotFoundException; import java.io. ...
- Java 连接、操控数据库总结(JDBC)
看到数据库连接不由得想起了大一末参加团队考核时的悲催经历~~,还记得当初傻傻地按照书本的代码打到 Eclipse 上,然后一运行就各种报错...报错后还傻傻地和书本的代码一遍又一遍地进行核对,发现无误 ...
随机推荐
- 对SNMP4J的一些封装
SNMP4J是一个开源的,用Java实现的snmp协议.其中提供了一下API,在这些API上面封装了一些方法,比如SNMP的get-request请求,get-next-request请求等 如果不了 ...
- Implementation: Quick Sort 2014-08-19
#include <stdio.h> void print(int *a, int start , int end); void quick_sort(int *a, int start, ...
- 用nodejs做一个svn密码修改页面
linux上配置好svn服务后,管理修改密码还得去手工修改passwd这个文件,略麻烦,其实网上应该有配套的web管理修改界面程序.但我想自己用nodejs写一个,因为用node不用配置复杂的服务器. ...
- linux下的动态链接库管理
LD_LIBRARY_PATH Linux环境变量名,该环境变量主要用于指定查找共享库(动态链接库)时除了默认路径之外的其他路径.(该路径在默认路径之前查找) 移植程序时的经常碰到需要使用一些特定的动 ...
- SQL Server ->> DISABLE索引后插入更新数据再REBUILD索引 和 保留索引直接插入更新数据的性能差异
之前对于“DISABLE索引后插入更新数据再REBUILD索引 和 保留索引直接插入更新数据的性能差异”这两种方法一直认为其实应该差不多,因为无论如何索引最后都需要被维护,只不过是个时间顺序先后的问题 ...
- Struts的学习-eclipse与idea与struts的连接
1.建立一个空白工程(里面是没有文件的). 可以在文件放置找到项目文件夹 2.点击托管项目到码云 (ps:没有码云帐号的自己注册) 3.按快捷键:ctrl+alt+shift+s 呼出项目结构管理器, ...
- June 08th 2017 Week 23rd Thursday
Life is like a beautiful melody, only the lyrics are messed up. 生命是首美丽的曲子,虽然歌词有些纠结. Now that we get ...
- OpenGL中的数据——Buffer
OpenGL中主要包括了两种数据——Buffer和Texture. Buffer用于储存线性数无类型据块,可以看成普通的内存块,而Texture则用于储存多维数据,一般储存图像或者其他数据. Buff ...
- sql server:取当前时间前10分钟之内的数据 dateadd()
当前时间 select GETDATE() 当前时间点前10分钟 dateadd() ,GETDATE()) 取当前时间点前10分钟以内的数据,且按创建时间倒序排 select * from tabl ...
- IOS VFL语言(页面布局)
● 什么是VFL语言 ● VFL全称是Visual Format Language,翻译过来是“可视化格式语言” ● VFL是苹果公司为了简化Autolayout的编码而推出的抽象语言 VFL ...