DbUtils是一个小型的类库,它设计用于使JDBC编程更加方便、简单。JDBC编程中,资源的关闭是显式的,极易导致编程错误,DbUtils把这些清理工作抽象出来,使得程序员编程时仅需要关心真正需要关心的,即:query和update数据。
相关API:
接口摘要
org.apache.commons.dbutils.ResultSetHandler
org.apache.commons.dbutils.RowProcessor:将ResultSet行转换为别的对象。
类摘要
org.apache.commons.dbutils.DbUtils:提供JDBC最常用的功能的工具类。
org.apache.commons.dbutils.BasicRowProcessor:RowProcessor接口的基本实现类。
org.apache.commons.dbutils.BeanProcessor:BeanProcessor匹配列名到Bean属性名,并转换结果集列到Bean对象的属性中。
org.apache.commons.dbutils.ProxyFactory:产生JDBC接口的代理实现。
org.apache.commons.dbutils.QueryLoader:属性文件加载器,主要用于加载属性文件中的 SQL 到内存中。
org.apache.commons.dbutils.QueryRunner:使用可插拔的策略执行SQL查询并处理结果集。
org.apache.commons.dbutils.ResultSetIterator:包装结果集为一个迭代器。
ResultSetHandler接口的实现类:
org.apache.commons.dbutils.handlers.AbstractListHandler:将ResultSet转为List的抽象类。
org.apache.commons.dbutils.handlers.ArrayHandler:将ResultSet转为一个Object[]的ResultSetHandler实现类。
org.apache.commons.dbutils.handlers.ArrayListHandler:将ResultSet转换为List
org.apache.commons.dbutils.handlers.BeanHandler:将ResultSet首行转换为一个JavaBean的ResultSetHandler实现类。
org.apache.commons.dbutils.handlers.BeanListHandler:将ResultSet转换为List
org.apache.commons.dbutils.handlers.ColumnListHandler:将ResultSet的一个列转换为List
org.apache.commons.dbutils.handlers.KeyedHandler:将ResultSet转换为Map
org.apache.commons.dbutils.wrappers.SqlNullCheckedResultSet:在每个getXXX方法上检查SQL NULL值的ResultSet包装类。
org.apache.commons.dbutils.wrappers.StringTrimmedResultSet:去除结果集中字符串左右空格的ResultSet包装类。
使用:由于使用Gradle构建,所以只需要修改build.gradle的依赖
compile group: 'commons-dbutils', name: 'commons-dbutils', version: '1.6'
SQL脚本:
mysql> SHOW CREATE TABLE persons;
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| persons | CREATE TABLE `persons` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 |
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.12 sec)
实体类:
package cn.bjut.entity;
/**
* Created by N3verL4nd on 2017/6/6.
*/
public class Person {
private int id;
private String name;
private int age;
public Person() {
}
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
测试类:
package cn.bjut.test;
import cn.bjut.entity.Person;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
/**
* Created by N3verL4nd on 2017/6/8.
*/
class DbUtil {
private static String url = "jdbc:mysql:///test?useUnicode=true&characterEncoding=UTF-8&useSSL=true";
private static String username = "root";
private static String password = "lgh123";
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
public class DBUtilsTest {
public static void testQuery() {
//创建连接
Connection conn = DbUtil.getConnection();
//创建SQL执行工具
QueryRunner queryRunner = new QueryRunner();
List list = null;
try {
//执行SQL查询,并获取结果
list = queryRunner.query(conn, "select * from persons", new BeanListHandler<>(Person.class));
} catch (SQLException e) {
e.printStackTrace();
}
if (list != null) {
//输出查询结果
list.forEach(System.out::println);
}
//关闭数据库连接
DbUtils.closeQuietly(conn);
}
public static void testUpdate() {
//创建连接
Connection conn = DbUtil.getConnection();
//创建SQL执行工具
QueryRunner queryRunner = new QueryRunner();
int rows = 0;
try {
//执行SQL插入
rows = queryRunner.update(conn, "INSERT INTO persons(name, age) VALUES(?, ?)", "阡陌", 24);
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("成功插入" + rows + "条数据!");
//关闭数据库连接
DbUtils.closeQuietly(conn);
}
public static void main(String[] args) {
testUpdate();
testQuery();
}
}
输出:
成功插入1条数据!
Person{id=1, name='lgh', age=30}
Person{id=2, name='xiya', age=20}
Person{id=3, name='芊漪', age=100}
Person{id=4, name='lgh', age=25}
Person{id=5, name='lgh', age=25}
Person{id=7, name='lgh', age=25}
Person{id=8, name='lgh', age=25}
Person{id=9, name='阡陌', age=24}
Process finished with exit code 0
当然也可以使用BeanHandler,将某一条记录转换为Bean
Connection connection = DbUtil.getConnection();
QueryRunner runner = new QueryRunner();
try {
Person person = runner.query(connection, "SELECT * FROM persons WHERE id = ?", new BeanHandler<>(Person.class), 1);
System.out.println(person);
} catch (SQLException e) {
e.printStackTrace();
}
DbUtils.closeQuietly(connection);
public <T> T query(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException { return this.<T>query(conn, false, sql, rsh, params); }通过观察源码,我们看到最后的params是可变长参数。
也可以使用MapListHandler,将结果映射为Map类型。
Connection connection = DbUtil.getConnection();
QueryRunner runner = new QueryRunner();
try {
Map map = runner.query(connection, "SELECT * FROM persons WHERE id = ?", new MapHandler(), 3);
System.out.println(map.get("id") + " " + map.get("name") + " " + map.get("age"));
} catch (SQLException e) {
e.printStackTrace();
}
DbUtils.closeQuietly(connection);
Connection connection = DbUtil.getConnection();
QueryRunner runner = new QueryRunner();
try {
List> list = runner.query(connection, "SELECT * FROM persons", new MapListHandler());
for (Map map : list) {
System.out.println(map.get("id") + " " + map.get("name") + " " + map.get("age"));
}
} catch (SQLException e) {
e.printStackTrace();
}
DbUtils.closeQuietly(connection);
参考:
http://gao-xianglong.iteye.com/blog/2166444