jdbc框架-dbutils的简单使用

jdbc框架-dbutils的简单使用

 

dbutils:是apache组织的一个工具类,jdbc的框架,更方便我们使用

使用步骤:
  1.导入jar包(commons-dbutils-1.4.jar)
  2.创建一个queryrunner类
    queryrunner作用:操作sql语句

    构造方法:
      new QueryRunner(Datasource ds);

  3.编写sql
  4.执行sql
    query(..):执行r操作
    update(...):执行cud操作

核心类或接口
  QueryRunner:类名
作用:操作sql语句


构造器:
  new QueryRunner(Datasource ds);

注意:
  底层帮我们创建连接,创建语句执行者 ,释放资源.


常用方法:
  query(..):
  update(..):

DbUtils:释放资源,控制事务 类
  closeQuietly(conn):内部处理了异常
  commitAndClose(Connection conn):提交事务并释放连接
....


 

示例一:insert

1.创建一个项目DataSourse

2.新建2个包,分别为com.util.hjh、com.dbutils.hjh

3.com.util.hjh包下放工具类DataSourseUtils.java;包com.dbutils.hjh放DbutilTest01.java

4.导入jar包(commons-dbutils-1.4.jar),buildPath。

 

DataSourseUtils.java源码:

package com.util.hjh;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourseUtils {
    //建立连接池ds
    private static ComboPooledDataSource ds =     new ComboPooledDataSource();
    
    //获取数据源
    public static DataSource getDataSourse() {
        return ds;
    }
    
    //获取连接
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
    
    //释放资源
    public static void closeResourse(Connection conn,Statement st) {
        try {
            if(st!=null) {
                st.close();
            }else {
                st = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(conn!=null) {
                conn.close();
            }else {
                conn = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    /**释放资源closeResourse(conn,ps)*/
    public static void closeResourse(Connection conn,PreparedStatement ps) {
        try {
            if(ps!=null) {
                ps.close();
            }else {
                ps = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(conn!=null) {
                conn.close();
            }else {
                conn = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**释放资源closeResourse(rs)*/
    public static void closeResourse(ResultSet rs) {
        try {
            if(rs!=null) {
                rs.close();
            }else {
                rs = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }    
}

 

 DbutilTest01.java源码:

package com.dbutils.hjh;

import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;
import com.util.hjh.DataSourseUtils;

public class DbutilsTest01 {
    @Test
    public void insert() throws SQLException {
        //创建QueryRunner对象,操作sql语句
        QueryRunner qr = new QueryRunner(DataSourseUtils.getDataSourse());
        
        //编写sql语句
        String sql = "insert into student values(?,?,?);";
        
        //执行sql
        int i = qr.update(sql,"07","wdc","79");
        
        System.out.println("插入了"+i+"行数据");
    }    
}

 

数据库表现为:

 

DBUtils用的最多的莫过于其结果集的处理,毕竟仅仅得到一个ResultSet屁用没有。而结果集的处理正是依赖于ResultSetHandler 接口及其实现类。  

 

ResultSetHandler:封装结果集 接口
  ArrayHandler, ArrayListHandler, BeanHandler, BeanListHandler, ColumnListHandler, KeyedHandler, MapHandler, MapListHandler, ScalarHandler

(了解)ArrayHandler, 将查询结果的第一条记录封装成数组,返回
(了解)ArrayListHandler, 将查询结果的每一条记录封装成数组,将每一个数组放入list中返回
★★BeanHandler, 将查询结果的第一条记录封装成指定的bean对象,返回
★★BeanListHandler, 将查询结果的每一条记录封装成指定的bean对象,将每一个bean对象放入list中 返回.
(了解)ColumnListHandler, 将查询结果的指定一列放入list中返回 
(了解)MapHandler, 将查询结果的第一条记录封装成map,字段名作为key,值为value 返回
★MapListHandler, 将查询结果的每一条记录封装map集合,将每一个map集合放入list中返回
★ScalarHandler,针对于聚合函数 例如:count(*) 返回的是一个Long值

 

ArrayHandler, 将查询结果的第一条记录封装成数组,返回

 

 

 

 

 ArrayHandlerTest.java源码:

package com.dbutils.hjh;

import java.sql.SQLException;
import java.util.Arrays;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.junit.Test;
import com.util.hjh.DataSourseUtils;

public class ArrayHandlerTest {
    @Test
    public void test() throws SQLException {
        //创建QueryRunner对象,操作sql语句
        QueryRunner qr = new QueryRunner(DataSourseUtils.getDataSourse());
        
        //编写sql语句
        String sql = "select * from student";
        
        //执行sql       ArrayHandler, 将查询结果的第一条记录封装成数组,返回
        Object [] query = qr.query(sql, new ArrayHandler());
        
        //打印
        System.out.println(Arrays.toString(query));    
    }
}

代码运行,console输出为:[1, hejh, 100]

 

 

ArrayListHandler, 将查询结果的每一条记录封装成数组,将每一个数组放入list中返回

 

ArrayListHandlerTest.java源码:

package com.dbutils.hjh;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.junit.Test;
import com.util.hjh.DataSourseUtils;

public class ArrayListHandlerTest {
    @Test
    public void test() throws SQLException {
        //创建QueryRunner对象,操作sql语句
        QueryRunner qr = new QueryRunner(DataSourseUtils.getDataSourse());
        
        //编写sql语句
        String sql = "select * from student";
        
        //执行sql       ArrayListHandler, 将查询结果的每一条记录封装成数组,将每一个数组放入list中返回
        List<Object[]> list = qr.query(sql, new ArrayListHandler());
        
        //打印
        for (Object[] obj : list) {
            System.out.println(Arrays.toString(obj));
        }    
    }
}

局部测试,代码运行,console输出为:

[1, hejh, 100]
[2, swy, 101]
[3, haha, 99]
[4, sansa, 88]
[5, zys, 88]
[6, yz, 95]
[7, wdc, 79]
[22, erya, 103]

 

 

 

★★BeanHandler, 将查询结果的第一条记录封装成指定的bean对象,返回(首先需要创建一个bean类)

Student的bean类:

package com.bean.hjh;

public class Student {
    private int id;
    private String name;
    private int grate;
    
    public Student() {}
    public Student(int id,String name,int grate) {
        this.id = id;
        this.name = name;
        this.grate = grate;
    }
    
    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 getGrate() {
        return grate;
    }
    public void setGrate(int grate) {
        this.grate = grate;
    }
    
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", grate=" + grate + "]";
    }
}

 

BeanHandlerTest.java源码:
package com.dbutils.hjh;

import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.junit.Test;
import com.util.hjh.DataSourseUtils;
import com.bean.hjh.Student;

public class BeanHandlerTest {
    @Test
    public void test() throws SQLException {
        //创建QueryRunner对象,操作sql语句
        QueryRunner qr = new QueryRunner(DataSourseUtils.getDataSourse());
        
        //编写sql语句
        String sql = "select * from student";
        
        //执行sql      BeanHandler, 将查询结果的第一条记录封装成指定的bean对象,返回 
        Student student =  qr.query(sql, new BeanHandler<>(Student.class));
        
        //打印
        System.out.println(student.toString());        
    }
}

console输出:Student [id=1, name=hejh, grate=100]

 

 

★★BeanListHandler, 将查询结果的每一条记录封装成指定的bean对象,将每一个bean对象放入list中 返回.

package com.dbutils.hjh;

import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;

import com.bean.hjh.Student;
import com.util.hjh.DataSourseUtils;

public class BeanListHandlerTest {
    @Test
    public void test() throws SQLException {
        //创建QueryRunner对象,操作sql语句
        QueryRunner qr = new QueryRunner(DataSourseUtils.getDataSourse());
        
        //编写sql语句
        String sql = "select * from student";
        
        //执行sql      ★★BeanListHandler, 将查询结果的每一条记录封装成指定的bean对象,将每一个bean对象放入list中 返回.
        List<Student> list =qr.query(sql, new BeanListHandler<>(Student.class));
        
        //打印
        for (Student student : list) {        
            System.out.println(student.toString());    
        }
    }
}

console输出:

Student [id=1, name=hejh, grate=100]
Student [id=2, name=swy, grate=101]
Student [id=3, name=haha, grate=99]
Student [id=4, name=sansa, grate=88]
Student [id=5, name=zys, grate=88]
Student [id=6, name=yz, grate=95]
Student [id=7, name=wdc, grate=79]
Student [id=22, name=erya, grate=103]

 

 

MapHandler, 将查询结果的第一条记录封装成map,字段名作为key,值为value 返回

案例:

数据库同上、项目结构同上,新增MapHandlerTest.java类

MapHandlerTest.java源码:

package com.dbutils.hjh;

import java.sql.SQLException;
import java.util.Map;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.junit.Test;
import com.util.hjh.DataSourseUtils;

public class MapHandlerTest {
    @Test
    public void test() throws SQLException {
        //创建QueryRunner对象,操作sql语句
        QueryRunner qr = new QueryRunner(DataSourseUtils.getDataSourse());
        
        //编写sql语句
        String sql = "select * from student";
        
        //执行sql   MapHandler, 将查询结果的第一条记录封装成map,字段名作为key,值为value 返回   
        Map<String,Object> map = qr.query(sql, new MapHandler());
        
        //打印
        System.out.println(map);        
    }
}

console输出为:

{grate=100, name=hejh, id=1}

 

 

 

MapListHandler, 将查询结果的每一条记录封装map集合,将每一个map集合放入list中返回

案例:

数据库同上、项目结构同上,新增MapListHandlerTest.java类

package com.dbutils.hjh;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.junit.Test;
import com.util.hjh.DataSourseUtils;

public class MapListHandlerTest {
    @Test
    public void test() throws SQLException {
        //创建QueryRunner对象,操作sql语句
        QueryRunner qr = new QueryRunner(DataSourseUtils.getDataSourse());
        
        //编写sql语句
        String sql = "select * from student";
        
        //执行sql  MapListHandler, 将查询结果的每一条记录封装map集合,将每一个map集合放入list中返回
        List<Map<String,Object>>  list =  qr.query(sql, new MapListHandler());
        //打印
        for (Map<String, Object> map : list) {            
            System.out.println(map);        
        }
    }
}

console输出为:

{grate=100, name=hejh, id=1}
{grate=101, name=swy, id=2}
{grate=99, name=haha, id=3}
{grate=88, name=sansa, id=4}
{grate=88, name=zys, id=5}
{grate=95, name=yz, id=6}
{grate=79, name=wdc, id=7}
{grate=103, name=erya, id=22}

 

 

ScalarHandler,针对于聚合函数 例如:count(*) 返回的是一个Long值

案例:

数据库同上、项目结构同上,新增ScalarHandlerTest.java类

package com.dbutils.hjh;

import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;
import com.util.hjh.DataSourseUtils;

public class ScalarHandlerTest {
    @Test
    public void test() throws SQLException {
        //创建QueryRunner对象,操作sql语句
        QueryRunner qr = new QueryRunner(DataSourseUtils.getDataSourse());
        
        //编写sql语句
        String sql = "select count(*)  from student";
        
        //执行sql   ScalarHandler,针对于聚合函数 例如:count(*) 返回的是一个Long值 
        Object obj =qr.query(sql, new ScalarHandler());
        
        //打印
        System.out.println(obj);   //console输出为:8
     System.out.println(obj.getClass().getName());//java.lang.Long 查看类型
} }

 

posted @ 2019-05-15 17:46  雪顶儿  阅读(594)  评论(0编辑  收藏  举报