【JDBC第9章】Apache-DBUtils實現CRUD操做

第9章:Apache-DBUtils實現CRUD操做

9.1 Apache-DBUtils簡介

  • commons-dbutils 是 Apache 組織提供的一個開源 JDBC工具類庫,它是對JDBC的簡單封裝,學習成本極低,而且使用dbutils能極大簡化jdbc編碼的工做量,同時也不會影響程序的性能。java

  • API介紹:
    • org.apache.commons.dbutils.QueryRunner
    • org.apache.commons.dbutils.ResultSetHandler
    • 工具類:org.apache.commons.dbutils.DbUtils
  • API包說明:sql

9.2 主要API的使用

9.2.1 DbUtils

  • DbUtils :提供如關閉鏈接、裝載JDBC驅動程序等常規工做的工具類,裏面的全部方法都是靜態的。主要方法以下:
    • public static void close(…) throws java.sql.SQLException: DbUtils類提供了三個重載的關閉方法。這些方法檢查所提供的參數是否是NULL,若是不是的話,它們就關閉Connection、Statement和ResultSet。
    • public static void closeQuietly(…): 這一類方法不只能在Connection、Statement和ResultSet爲NULL狀況下避免關閉,還能隱藏一些在程序中拋出的SQLEeception。
    • public static void commitAndClose(Connection conn)throws SQLException: 用來提交鏈接的事務,而後關閉鏈接
    • public static void commitAndCloseQuietly(Connection conn): 用來提交鏈接,而後關閉鏈接,而且在關閉鏈接時不拋出SQL異常。
    • public static void rollback(Connection conn)throws SQLException:容許conn爲null,由於方法內部作了判斷
    • public static void rollbackAndClose(Connection conn)throws SQLException
    • rollbackAndCloseQuietly(Connection)
    • public static boolean loadDriver(java.lang.String driverClassName):這一方裝載並註冊JDBC驅動程序,若是成功就返回true。使用該方法,你不須要捕捉這個異常ClassNotFoundException。

9.2.2 QueryRunner類

  • 該類簡單化了SQL查詢,它與ResultSetHandler組合在一塊兒使用能夠完成大部分的數據庫操做,可以大大減小編碼量。數據庫

  • QueryRunner類提供了兩個構造器:
    • 默認的構造器
    • 須要一個 javax.sql.DataSource 來做參數的構造器
  • QueryRunner類的主要方法:
    • 更新
      • public int update(Connection conn, String sql, Object... params) throws SQLException:用來執行一個更新(插入、更新或刪除)操做。
      • ......
    • 插入
      • public T insert(Connection conn,String sql,ResultSetHandler rsh, Object... params) throws SQLException:只支持INSERT語句,其中 rsh - The handler used to create the result object from the ResultSet of auto-generated keys. 返回值: An object generated by the handler.即自動生成的鍵值
      • ....
    • 批處理
      • public int[] batch(Connection conn,String sql,Object[][] params)throws SQLException: INSERT, UPDATE, or DELETE語句
      • public T insertBatch(Connection conn,String sql,ResultSetHandler rsh,Object[][] params)throws SQLException:只支持INSERT語句
      • .....
    • 查詢
      • public Object query(Connection conn, String sql, ResultSetHandler rsh,Object... params) throws SQLException:執行一個查詢操做,在這個查詢中,對象數組中的每一個元素值被用來做爲查詢語句的置換參數。該方法會自行處理 PreparedStatement 和 ResultSet 的建立和關閉。
      • ......
  • 測試apache

// 測試添加
@Test
public void testInsert() throws Exception {
    QueryRunner runner = new QueryRunner();
    Connection conn = JDBCUtils.getConnection3();
    String sql = "insert into customers(name,email,birth)values(?,?,?)";
    int count = runner.update(conn, sql, "何成飛", "he@qq.com", "1992-09-08");

    System.out.println("添加了" + count + "條記錄");
        
    JDBCUtils.closeResource(conn, null);

}
// 測試刪除
@Test
public void testDelete() throws Exception {
    QueryRunner runner = new QueryRunner();
    Connection conn = JDBCUtils.getConnection3();
    String sql = "delete from customers where id < ?";
    int count = runner.update(conn, sql,3);

    System.out.println("刪除了" + count + "條記錄");
        
    JDBCUtils.closeResource(conn, null);

}

9.2.3 ResultSetHandler接口及實現類

  • 該接口用於處理 java.sql.ResultSet,將數據按要求轉換爲另外一種形式。api

  • ResultSetHandler 接口提供了一個單獨的方法:Object handle (java.sql.ResultSet .rs)。數組

  • 接口的主要實現類:ide

    • ArrayHandler:把結果集中的第一行數據轉成對象數組。
    • ArrayListHandler:把結果集中的每一行數據都轉成一個數組,再存放到List中。
    • BeanHandler:將結果集中的第一行數據封裝到一個對應的JavaBean實例中。
    • BeanListHandler:將結果集中的每一行數據都封裝到一個對應的JavaBean實例中,存放到List裏。
    • ColumnListHandler:將結果集中某一列的數據存放到List中。
    • KeyedHandler(name):將結果集中的每一行數據都封裝到一個Map裏,再把這些map再存到一個map裏,其key爲指定的key。
    • MapHandler:將結果集中的第一行數據封裝到一個Map裏,key是列名,value就是對應的值。
    • MapListHandler:將結果集中的每一行數據都封裝到一個Map裏,而後再存放到List
    • ScalarHandler:查詢單個值對象
  • 測試工具

/*
 * 測試查詢:查詢一條記錄
 * 
 * 使用ResultSetHandler的實現類:BeanHandler
 */
@Test
public void testQueryInstance() throws Exception{
    QueryRunner runner = new QueryRunner();

    Connection conn = JDBCUtils.getConnection3();
        
    String sql = "select id,name,email,birth from customers where id = ?";
        
    //
    BeanHandler<Customer> handler = new BeanHandler<>(Customer.class);
    Customer customer = runner.query(conn, sql, handler, 23);
    System.out.println(customer);   
    JDBCUtils.closeResource(conn, null);
}
/*
 * 測試查詢:查詢多條記錄構成的集合
 * 
 * 使用ResultSetHandler的實現類:BeanListHandler
 */
@Test
public void testQueryList() throws Exception{
    QueryRunner runner = new QueryRunner();

    Connection conn = JDBCUtils.getConnection3();
        
    String sql = "select id,name,email,birth from customers where id < ?";
        
    //
    BeanListHandler<Customer> handler = new BeanListHandler<>(Customer.class);
    List<Customer> list = runner.query(conn, sql, handler, 23);
    list.forEach(System.out::println);
        
    JDBCUtils.closeResource(conn, null);
}
/*
 * 自定義ResultSetHandler的實現類
 */
@Test
public void testQueryInstance1() throws Exception{
    QueryRunner runner = new QueryRunner();

    Connection conn = JDBCUtils.getConnection3();
        
    String sql = "select id,name,email,birth from customers where id = ?";
        
    ResultSetHandler<Customer> handler = new ResultSetHandler<Customer>() {

        @Override
        public Customer handle(ResultSet rs) throws SQLException {
            System.out.println("handle");
//          return new Customer(1,"Tom","tom@126.com",new Date(123323432L));
                
            if(rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String email = rs.getString("email");
                Date birth = rs.getDate("birth");
                    
                return new Customer(id, name, email, birth);
            }
            return null;
                
        }
    };
        
    Customer customer = runner.query(conn, sql, handler, 23);
        
    System.out.println(customer);
        
    JDBCUtils.closeResource(conn, null);
}
/*
 * 如何查詢相似於最大的,最小的,平均的,總和,個數相關的數據,
 * 使用ScalarHandler
 * 
 */
@Test
public void testQueryValue() throws Exception{
    QueryRunner runner = new QueryRunner();

    Connection conn = JDBCUtils.getConnection3();
        
    //測試一:
//  String sql = "select count(*) from customers where id < ?";
//  ScalarHandler handler = new ScalarHandler();
//  long count = (long) runner.query(conn, sql, handler, 20);
//  System.out.println(count);
        
    //測試二:
    String sql = "select max(birth) from customers";
    ScalarHandler handler = new ScalarHandler();
    Date birth = (Date) runner.query(conn, sql, handler);
    System.out.println(birth);
        
    JDBCUtils.closeResource(conn, null);
}
相關文章
相關標籤/搜索