JAVA中DBUtils的QueryRunner类实现增删改查详解

一.QueryRunner类实现增删改

连接池代码:JdbcUtil.java

package com.wb.util;

/**
 * c3p0,dbcp,druid
 */
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

/**
 * 绝对不能使用单例
 * 
 * @author Administrator 硬编码
 */
public class JdbcUtil {
    private static Connection con = null;
    private static DataSource ds = null;
    private static Properties pt = null;
    static {
        // 1.获得当前类的加载器
        ClassLoader cl = JdbcUtil.class.getClassLoader();
        // 通过该加载器得到一个输入流
        InputStream in = cl.getResourceAsStream("jdbc.properties");
        // 通过输入创一个properties对象
        pt = new Properties();
        try {
            pt.load(in);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static Connection getCon() {

        if (ds == null) {
            try {
                ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(pt);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            return ds.getConnection();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    public static void closeCon(Connection con) {
        try {
            con.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

具体使用模板:

   publicstaticvoidmain(String[] args)throws Exception{//使用自己的工具类,获取数据库的连接对象

Connection conn = MyJDBCUtils.getConnection();//创建QueryRunner类对象
QueryRunner qr =newQueryRunner(); 
String sql ="UPDATE gjp_ledger set money=? , ldesc=? where lid=?"; 
Object[] params ={998,"买钻石",3};int result = qr.update(conn, sql, params); 
System.out.println(result); 
DbUtils.close(conn);}

二.QueryRunner类获取查询结果集ResultSetHandler

1.常用Handler

  • ArrayHandler 将结果集第一行转成对象数组
  publicstaticvoidmain(String[] args)throws Exception{ 
  Connection conn = MyJDBCUtils.getConnection(); 
  String sql ="SELECT * FROM gjp_ledger where lid=?"; 
  //结果集处理方式,ArrayHandler 第一行转成对象数组
  QueryRunner qr =newQueryRunner(); 
  Object[] objects = qr.query(conn, sql,newArrayHandler(),3);
  for(Object obj : objects){ 
  System.out.println(obj); 
  } 
  }
  • ArrayListHandler 将结果集中的每一行数据都转成一个对象数组,再将转成的多个对象数组存放到List
  publicstaticvoidmain(String[] args)throws Exception{ 
  Connection conn = MyJDBCUtils.getConnection(); 
String sql ="SELECT * FROM gjp_ledger"; 
QueryRunner qr =newQueryRunner();//执行query方法,传递连接对象,SQL语句,结果集处理方式
ArrayListHandler 
List<Object[]> list = qr.query(conn, sql,newArrayListHandler());for(Object[] objects : list){for(Object obj : objects){ 
System.out.print(obj+" ");} 
System.out.println();}}
  • BeanHandler 将结果集第一行数据封装到一个对应的业务类实例中
    (1): 定义业务数据类Ledger(实体类,javaBean)
publicclassLedger{//要生成空参、有参构造、set和get方法、toString方法
privateint lid;private String parent;privatedouble money;privateint sid;private String account;private String createtime;private String ldesc;}

(2)测试案例代码

publicstaticvoidmain(String[] args)throws Exception{ 
Connection conn = MyJDBCUtils.getConnection(); 
String sql ="SELECT * FROM gjp_ledger"; 
QueryRunner qr =newQueryRunner();//BeanHandler泛型,构造方法(和反射有关系的对象) 
Ledger legder = qr.query(conn, sql,newBeanHandler<Ledger>(Ledger.class)); 
System.out.println(legder);}
  • BeanListHandler 将结果集中的每一行数据都封装到一个对应的业务类实例中,再将多个业务类实例对象存放到List里。
publicstaticvoidmain(String[] args)throws Exception { 
Connection conn = MyJDBCUtils.getConnection(); 
String sql ="SELECT * FROM gjp_ledger";//结果集处理方式,BeanListHandler 每一行数据封装到业务数据类中
QueryRunner qr =newQueryRunner(); 
List list = qr.query(conn, sql,newBeanListHandler(Ledger.class));for(Ledger ledger : list){ 
System.out.println(ledger);}}
  • MapHandler 将结果集中的第一行数据封装到一个Map中,key是列名,value是对应的值。
  publicstaticvoidmain(String[] args)throws Exception { 
Connection conn = MyJDBCUtils.getConnection(); 
String sql ="SELECT * FROM gjp_ledger";//结果集处理方式,MapHandler 封装到一个Map集合中,存储键值对集合
QueryRunner qr =newQueryRunner(); 
Map<String,Object> map = qr.query(conn, sql,newMapHandler());for(String key : map.keySet()){ 
System.out.println(key+" "+map.get(key));}}
  • MapListHandler 将结果集中的每一行数据都封装到一个Map里,然后再将多个Map存放到List
   publicstaticvoidmain(String[] args)throws Exception{ 
Connection conn = MyJDBCUtils.getConnection(); 
String sql ="SELECT * FROM gjp_ledger";//结果集处理方式,MapListHandler 数据中的每一行封装成Map集合,多个Map集合存储到List集合
QueryRunner qr =newQueryRunner(); 
List<Map<String,Object>> list = qr.query(conn, sql,newMapListHandler());for(Map<String,Object> map : list){for(String key : map.keySet()){ 
System.out.print(key+" "+map.get(key));} 
System.out.println();

多表联合查询

 QueryRunner qr = new QueryRunner();

    @Override
    public List<Emp> getEmpList(Integer pageSize, Integer pageIndex, String empName) {
        List<Emp> empList = new ArrayList<Emp>();
       /*
        //使用new BeanListHandler<>(Emp.class);会导致集合里面字段为空
        Connection con = JdbcUtil.getCon();
        String sql = "select emp_id empId,emp_name empName,emp_phone empPhone,emp_age empAge,emp_sex empSex,e.depa_id depaId, d.depa_name depaName  FROM emp e INNER JOIN depa d ON e.depa_id=d.depa_id WHERE e.emp_name like ? limit ?,?";
        try {
            empList = qr.query(con, sql, new BeanListHandler<>(Emp.class),
                    empName == null || "".equals(empName) ? "%%" : "%" + empName + "%",
                    (pageIndex - 1) * pageSize, pageSize);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.closeCon(con);
        }
        for (int i = 0; i < empList.size(); i++) {
            System.out.println(empList.get(i));
        }*/
        
        //使用 new MapListHandler() 需要手动遍历
        Connection con = JdbcUtil.getCon();
        String sql = "select emp_id,emp_name,emp_phone,emp_age,emp_sex,e.depa_id, depa_name FROM emp e INNER JOIN depa d ON e.depa_id=d.depa_id WHERE e.emp_name like ? limit ?,?";
        try {
            List<Map<String,Object>> list = qr.query(con, sql, new MapListHandler(),
                    empName == null || "".equals(empName) ? "%%" : "%" + empName + "%",
                    (pageIndex - 1) * pageSize, pageSize);
           for(Map<String,Object> map:list){
               Emp emp = new Emp();
               for(String key: map.keySet()){
                   switch (key) {
                case "emp_id":
                    emp.setEmpId((Integer) map.get(key));
                    break;
                case "emp_sex":
                    emp.setEmpSex((String) map.get(key));
                    break;
                case "emp_age":
                    emp.setEmpAge((Integer) map.get(key));
                    break;
                case "emp_phone":
                    emp.setEmpPhone((String) map.get(key));
                    break;
                case "emp_name":
                    emp.setEmpName((String) map.get(key));
                    break;
                case "depa_id":
                    emp.setDepaId((Integer) map.get(key));
                    break;
                case "depa_name":
                    emp.setDepaName((String) map.get(key));
                    break;

                default:
                    System.out.println("发生异常");
                    break;
                }
                   //System.out.println(key+"---"+map.get(key));
               }
               empList.add(emp);
           }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.closeCon(con);
        }
        for (int i = 0; i < empList.size(); i++) {
            System.out.println(empList.get(i));
        }
        return empList;
    }

你可能感兴趣的:(Java)