1. ResultSetHandler 的作用: QueryRunner 的 query 方法的返回值最终取决于
query 方法的 ResultHandler 参数的 hanlde 方法的返回值.
2. BeanListHandler: 把结果集转为一个 Bean 的 List, 并返回. Bean 的类型在
创建 BeanListHanlder 对象时以 Class 对象的方式传入. 可以适应列的别名来映射
JavaBean 的属性名:
String sql = "SELECT id, name customerName, email, birth " +
"FROM customers WHERE id = ?";
BeanListHandler(Class<T> type)
3. BeanHandler: 把结果集转为一个 Bean, 并返回. Bean 的类型在创建 BeanHandler
对象时以 Class 对象的方式传入
BeanHandler(Class<T> type)
4. MapHandler: 把结果集转为一个 Map 对象, 并返回. 若结果集中有多条记录, 仅返回
第一条记录对应的 Map 对象. Map 的键: 列名(而非列的别名), 值: 列的值
5. MapListHandler: 把结果集转为一个 Map 对象的集合, 并返回.
Map 的键: 列名(而非列的别名), 值: 列的值
6. ScalarHandler: 可以返回指定列的一个值或返回一个统计函数的值.
首先看链接数据库的工具类JdbcTools
package com.godinsec;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* JDBC 的工具类
*
* 其中包含: 获取数据库连接, 关闭数据库资源等方法.
*/
public class JdbcTools {
private static DataSource dataSource = null;
// 数据库连接池应只被初始化一次.
static {
dataSource = new ComboPooledDataSource("helloc3p0");
}
public static Connection getConnection() throws Exception {
return dataSource.getConnection();
}
public static void releaseDB(ResultSet resultSet, Statement statement,
Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
// 数据库连接池的 Connection 对象进行 close 时
// 并不是真的进行关闭, 而是把该数据库连接会归还到数据库连接池中.
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
c3p0-config.xml
<c3p0-config>
<named-config name="helloc3p0">
<property name="user">rootproperty>
<property name="password">rootproperty>
<property name="driverClass">com.mysql.jdbc.Driverproperty>
<property name="jdbcUrl">jdbc:mysql:///mydatabaseproperty>
<property name="acquireIncrement">5property>
<property name="initialPoolSize">5property>
<property name="minPoolSize">5property>
<property name="maxPoolSize">10property>
<property name="maxStatements">20property>
<property name="maxStatementsPerConnection">5property>
named-config>
c3p0-config>
构建一个bean类Customer
private Integer id;
private String name;
private String email;
private Date birth;
接下来看几个需要了解的方法
/**
* QueryLoader: 可以用来加载存放着 SQL 语句的资源文件.
* 使用该类可以把 SQL 语句外置化到一个资源文件中. 以提供更好的解耦
* @throws IOException
*/
@Test
public void testQueryLoader() throws IOException{
// / 代表类路径的根目录.
Map sqls =
QueryLoader.instance().load("/sql.properties");
String updateSql = sqls.get("UPDATE_CUSTOMER");
System.out.println(updateSql);
}
sql.properties
UPDATE_CUSTOMER=UPDATE customer SET name = ? WHERE id = ?
日志输出如下
UPDATE customer SET name = ? WHERE id = ?
/**
* 测试 QueryRunner 的 query 方法
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testResultSetHandler(){
String sql = "SELECT id, name, email, birth " +
"FROM customer";
//1. 创建 QueryRunner 对象
QueryRunner queryRunner = new QueryRunner();
Connection conn = null;
try {
conn = JdbcTools.getConnection();
/**
* 2. 调用 query 方法:
* ResultSetHandler 参数的作用: query 方法的返回值直接取决于
* ResultSetHandler 的 hanlde(ResultSet rs) 是如何实现的. 实际上, 在
* QueryRunner 类的 query 方法中也是调用了 ResultSetHandler 的 handle()
* 方法作为返回值的。
*/
Object object = queryRunner.query(conn, sql,
new ResultSetHandler(){
@Override
public Object handle(ResultSet rs) throws SQLException {
List customers = new ArrayList<>();
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
String email = rs.getString(3);
Date birth = rs.getDate(4);
System.out.println(id+","+name+","+email+","+birth);
Customer customer =
new Customer(id, name, email, birth);
customers.add(customer);
}
return customers;
}
}
);
System.out.println(object);
} catch (Exception e) {
e.printStackTrace();
} finally{
JdbcTools.releaseDB(null, null, conn);
}
}
log输出日志如下
1,aaa,aaa,2016-10-05
2,bbb,bbb,2016-10-11
[Customer [id=1, name=aaa, email=aaa, birth=2016-10-05], Customer [id=2, name=bbb, email=bbb, birth=2016-10-11]]
删除如下:
/**
* 测试 QueryRunner 类的 update 方法
* 该方法可用于 INSERT, UPDATE 和 DELETE
*/
@Test
public void testQueryRunnerUpdate() {
//1. 创建 QueryRunner 的实现类
QueryRunner queryRunner = new QueryRunner();
String sql = "DELETE FROM customer " +
"WHERE id IN (?,?)";
Connection connection = null;
try {
connection = JdbcTools.getConnection();
//2. 使用其 update 方法
int update = queryRunner.update(connection,
sql, 1, 2);
System.out.println("update:"+update);
} catch (Exception e) {
e.printStackTrace();
} finally{
JdbcTools.releaseDB(null, null, connection);
}
}
/**
* 测试 ResultSetHandler 的 BeanListHandler 实现类
* BeanListHandler: 把结果集转为一个 Bean 的 List. 该 Bean
* 的类型在创建 BeanListHandler 对象时传入:
*
* new BeanListHandler<>(Customer.class)
*
*/
@Test
public void testBeanListHandler(){
String sql = "SELECT id, name, email, birth " +
"FROM customer";
//1. 创建 QueryRunner 对象
QueryRunner queryRunner = new QueryRunner();
Connection conn = null;
try {
conn = JdbcTools.getConnection();
Object object = queryRunner.query(conn, sql,
new BeanListHandler<>(Customer.class));
System.out.println(object);
ArrayList customers = (ArrayList) object;
for (int i = 0; i < customers.size(); i++) {
Customer customer = customers.get(i);
System.out.println(customer.getName());
}
} catch (Exception e) {
e.printStackTrace();
} finally{
JdbcTools.releaseDB(null, null, conn);
}
}
输出如下:
[Customer [id=1, name=aaa, email=aaa, birth=2016-10-05], Customer [id=2, name=bbb, email=bbb, birth=2016-10-11]]
aaa
bbb
/**
* BeanHandler: 把结果集的第一条记录转为创建 BeanHandler 对象时传入的 Class 参数对应的对象.
*/
@Test
public void testBeanHanlder() {
QueryRunner queryRunner = new QueryRunner();
Connection connection = null;
try {
connection = JdbcTools.getConnection();
String sql = "SELECT id, name, email, birth "
+ "FROM customer WHERE name = ?";
@SuppressWarnings("unchecked")
Customer customer = queryRunner.query(connection, sql,
new BeanHandler(Customer.class), "bbb");
System.out.println(customer);
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcTools.releaseDB(null, null, null, connection);
}
}
输出如下:
Customer [id=2, name=bbb, email=bbb, birth=2016-10-26]
@Test
public void testMapHandler(){
Connection connection = null;
QueryRunner queryRunner = new QueryRunner();
String sql = "SELECT id, name, email, birth " +
"FROM customer WHERE id = ?";
try {
connection = JdbcTools.getConnection();
Map map = queryRunner.query(connection,
sql, new MapHandler(), 2);
System.out.println(map);
} catch (Exception e) {
e.printStackTrace();
} finally{
JdbcTools.releaseDB(null, null, connection);
}
}
输出如下:
{id=2, birth=2016-10-11, email=bbb, name=bbb}
@Test
public void testMapListHandler(){
Connection connection = null;
QueryRunner queryRunner = new QueryRunner();
String sql = "SELECT id, name, email, birth " +
"FROM customer";
try {
connection = JdbcTools.getConnection();
List
输出如下:
[{id=1, birth=2016-10-05, email=aaa, name=aaa}, {id=2, birth=2016-10-26, email=bbb, name=bbb}]
@Test
public void testScalarHandler(){
Connection connection = null;
QueryRunner queryRunner = new QueryRunner();
String sql = "SELECT name FROM customer " +
"WHERE id = ?";
try {
connection = JdbcTools.getConnection();
Object count = queryRunner.query(connection, sql,
new ScalarHandler(), 2);
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();
} finally{
JdbcTools.releaseDB(null, null, connection);
}
}
输出如下:
bbb
/*
* 结果集第二种处理方法,ArrayListHandler
* 将结果集的每一行,封装到对象数组中, 出现很多对象数组
* 对象数组存储到List集合
*/
public static void arrayListHandler()throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "SELECT * FROM sort";
//调用query方法,结果集处理的参数上,传递实现类ArrayListHandler
//方法返回值 每行是一个对象数组,存储到List
List
/*
* 结果集第五种处理方法,ColumnListHandler
* 结果集,指定列的数据,存储到List集合
* List
public static void columnListHandler()throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "SELECT * FROM sort ";
//调用方法 query,传递结果集实现类ColumnListHandler
//实现类构造方法中,使用字符串的列名
List