DBUtiles中的简单使用(QueryRunner和ResultSetHandler的手动实现)
DBUtiles是一个很好的处理JDBC的工具类。(DbUtils is a small set of classes designed to make working with JDBC easier )
DBUtiles中的QueryRunner和ResultSetHandler的手动实现
其中比较常用的就是QueryRunner类和ResultSetHandler接口。通过它们可以很方便的实现JDBC的功能。
QueryRunner类,有四个构造方法,其中有的构造方法可以接受一个DataSource
例如:QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
当我们获得QueryRunner的实例对象时,就能通过QueryRunner类的方法方便的操作数据库。QueryRunner类主要有三类方法,batch()方法,query()方法,update()方法。
例如:
- QueryRunner runner=new QueryRunner(new ComboPooledDataSource());
- runner.update("insert into account values(null,?,?)","e",888);
- runner.update("update account set money=0 where name=?", "e");
查询的方法稍微麻烦一点,因为我们需要对查询到的结果集进行设置。通常需要把结果集ResultSet封装到JavaBean或者集合或者数组中。
查看一个方法: <T> T query(String sql, ResultSetHandler<T> rsh, Object... params)
这里第一个参数是sql语句字符串,第二个参数是一个实现了ResultSetHandler接口的类对象,第三个参数是Object类型的可变参数。返回值是一个T类型。
如果我们用的eclipse或者MyEclipse 鼠标放到ResutlSetHandlet上面,按F2,会有针对T的说明。<T> the target type the input ResultSet will be converted to.
意思是,T 代表 ResultSet结果集要装入的目标类型。也就是我们前面提到的数组,集合,甚至javabean.
下面用一段代码来实现把结果集装入一个List数组中。其中Account是一个javaBean,符合account表。
- public static List test2() throws Exception{
- QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
- return runner.query("select * from account where name=?",new ResultSetHandler<List<Account>>(){
- public List<Account> handle(ResultSet rs) throws SQLException {
- List<Account> list = new ArrayList<Account>();
- while(rs.next()){
- Account acc = new Account();
- acc.setId(rs.getInt("id"));
- acc.setName(rs.getString("name"));
- acc.setMoney(rs.getDouble("money"));
- list.add(acc);
- }
- return list;
- }
- } , "a");
- }
接下来,我们用两段代码来模拟QueryRunner和ResultSetHandler的实现原理。
- package cn.itheima.dbutils;
- import java.sql.Connection;
- import java.sql.ParameterMetaData;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;
- import javax.sql.DataSource;
- import cn.itheima.domain.Account;
- import com.mchange.v2.c3p0.ComboPooledDataSource;
- public class MyQueryRunner {
- private DataSource source = null;
- public MyQueryRunner(DataSource source) {
- this.source = source;
- }
- //查询原理:利用MyResourceHandler处理利用sql和objs拼写出来的sql语句查询出来的resultSet,处理
- public <T> T query(String sql,MyResultSetHandler<T> handler,Object ...objs){
- Connection conn = null;
- PreparedStatement ps = null;
- ResultSet rs = null;
- try {
- conn = source.getConnection();
- ps = conn.prepareStatement(sql);
- ParameterMetaData metaData = ps.getParameterMetaData();
- for(int i=1;i<=metaData.getParameterCount();i++){
- ps.setObject(i, objs[i-1]);
- }
- rs = ps.executeQuery();
- return handler.handle(rs);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException();
- } finally {
- if (rs != null) {
- try {
- rs.close();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- rs = null;
- }
- }
- if (ps != null) {
- try {
- ps.close();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- ps = null;
- }
- }
- if (conn != null) {
- try {
- conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- conn = null;
- }
- }
- }
- }
- public int update(String sql,Object ...objs){
- Connection conn = null;
- PreparedStatement ps = null;
- try{
- conn = source.getConnection();
- ps = conn.prepareStatement(sql);
- ParameterMetaData metaData = ps.getParameterMetaData();
- for(int i=1;i<=metaData.getParameterCount();i++){
- ps.setObject(i, objs[i-1]);
- }
- return ps.executeUpdate();
- }catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException();
- }finally{
- if(ps!=null){
- try {
- ps.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }finally{
- ps = null;
- }
- }
- if(conn!=null){
- try {
- conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }finally{
- conn = null;
- }
- }
- }
- }
- }
MyResultSetHandler接口
- package cn.itheima.dbutils;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- public interface MyResultSetHandler <T>{
- T handle(ResultSet rs)throws SQLException;
- }
当然,实际应用中没有这么麻烦。因为DBUtils已经帮我们实现了很多ResultSetHandler的实现类。通过这些类可以很方便的对结果集进行封装。
ResultSetHandler的实现类
- //1.ArrayHandler 将查询结果每一行转换为一个数组对象返回
- //ResultSetHandler implementation that converts a ResultSet into an Object[]. This class is thread safe.
- Object[] objs = runner.query("select * from account where name=?",new ArrayHandler() , "c");
- System.out.println(objs);
- //2.ArrayListHandler 将查询结果的每一行转换为一个Object[]数组,然后装入一个ArrayList集合
- //ResultSetHandler implementation that converts the ResultSet into a List of Object[]s. This class is thread safe.
- List<Object[]> list = runner.query("select * from account",new ArrayListHandler() );
- System.out.println(list);
- //手动实现ArrayListHandler的功能
- public static List test2() throws Exception{
- QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
- return runner.query("select * from account where name=?",new ResultSetHandler<List<Account>>(){
- public List<Account> handle(ResultSet rs) throws SQLException {
- List<Account> list = new ArrayList<Account>();
- while(rs.next()){
- Account acc = new Account();
- acc.setId(rs.getInt("id"));
- acc.setName(rs.getString("name"));
- acc.setMoney(rs.getDouble("money"));
- list.add(acc);
- }
- return list;
- }
- } , "a");
- }
- //3.BeanHandler,将查询结果的第一行转换为一个JavaBean对象返回
- //ResultSetHandler implementation that converts the first ResultSet row into a JavaBean. This class is thread safe.
- Account acc = runner.query("select * from account where name=?",new BeanHandler<Account>(Account.class) , "c");
- System.out.println(acc);
- //4.BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。
- //ResultSetHandler implementation that converts a ResultSet into a List of beans. This class is thread safe.
- List<Account> acclist = runner.query("select * from account",new BeanListHandler<Account>(Account.class) );
- System.out.println(acclist);
- //5.MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
- //ResultSetHandler implementation that converts the first ResultSet row into a Map. This class is thread safe.
- Map map = runner.query("select * from account",new MapHandler() );
- System.out.println(map);
- //6.MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List
- //ResultSetHandler implementation that converts a ResultSet into a List of Maps. This class is thread safe
- List<Map<String, Object>> maplist = runner.query("select * from account",new MapListHandler() );
- System.out.println(maplist);
- //7.ColumnListHandler:将结果集中某一列的数据存放到List中。
- //ResultSetHandler implementation that converts one ResultSet column into a List of Objects. This class is thread safe.
- List<Object> columnList = runner.query("select * from account",new ColumnListHandler(2) );
- System.out.println(columnList);
- //8.KeyedHandler(name):将结果集中的每一行数据都封装到一个Map里(List<Map>),再把这些map再存到一个map里,其key为指定的列。
- //ResultSetHandler implementation that returns a Map of Maps. ResultSet rows are converted into Maps which are then stored in a Map under the given key.
- Map<Object, Map<String, Object>> keymap = runner.query("select * from account",new KeyedHandler("id") );
- System.out.println(keymap);
- //9.ScalarHandler: 单值查询
- //ResultSetHandler implementation that converts one ResultSet column into an Object. This class is thread safe.
- //select count(*) from account;
- Long count = (Long)runner.query("select count(*) from account",new ScalarHandler(1) );
- System.out.println(count);