1. 程式人生 > 實用技巧 >【JDBC核心】commons-dbutils

【JDBC核心】commons-dbutils

commons-dbutils

簡介

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

主要類:

  • QueryRunner:提供資料庫操作的一些過載的 update()query() 方法;
  • ResultSetHandler:此介面用於處理資料庫查詢結果得到的結果集,不同的結果集有不同的子類實現;
  • DbUtils:提供如關閉連線、裝載 JDBC 驅動程式等常規工作的工具類,裡面的所有方法都是靜態的。

使用

QueryRunner 類

  • 該類簡化了 SQL 查詢,它與 ResultSetHandler 組合在一起使用可以完成大部分的資料庫操作,能夠大大減少編碼量**。
  • 該類提供了兩個構造器:
    • 預設的構造器;
    • 需要一個 javax.sql.DataSource 來作引數的構造器;
  • 主要方法:
    • 更新
      • public int update(Connection conn, String sql, Object... params) throws SQLException 用來執行一個更新(插入、更新或刪除)操作。
    • 插入
      • public <T> T insert(Connection conn,String sql,ResultSetHandler<T> rsh, Object... params) throws SQLException
        只支援插入操作。
    • 批處理
      • public int[] batch(Connection conn,String sql,Object[][] params)throws SQLException 插入、更新或刪除操作。
      • public <T> T insertBatch(Connection conn,String sql,ResultSetHandler<T> rsh,Object[][] params)throws SQLException 只支援插入操作。
    • 查詢
      • public Object query(Connection conn, String sql, ResultSetHandler rsh,Object... params) throws SQLException
        執行一個查詢操作,在這個查詢中,物件陣列中的每個元素值被用來作為查詢語句的置換引數。該方法會自行處理 PreparedStatement 和 ResultSet 的建立和關閉。

ResultSetHandler 介面

  • 該介面用於處理 java.sql.ResultSet,將資料按要求轉換為另一種形式;
  • 主要實現類:
    • 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 查詢單個值物件。
package cn.parzulpan.jdbc.ch09;

import cn.parzulpan.jdbc.bean.Customer;
import cn.parzulpan.jdbc.util.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.*;
import org.junit.Test;

import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @Author : parzulpan
 * @Time : 2020-12-01
 * @Desc : DBUtils QueryRunner 使用
 */

public class QueryRunnerTest {

    // 插入記錄
    @Test
    public void testInsert() {
        Connection connection = null;
        try {
            connection = JDBCUtils.getDruidConnection();

            QueryRunner queryRunner = new QueryRunner();
            String sql = "insert into customers(name,email,birth)values(?,?,?)";
            int update = queryRunner.update(connection, sql, "勁兒", "[email protected]", "1995-12-29");
            System.out.println("添加了 " + update + " 條記錄");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection, null);
        }
    }

    // 刪除記錄
    @Test
    public void testDelete() {
        Connection connection = null;
        try {
            connection = JDBCUtils.getDruidConnection();

            QueryRunner queryRunner = new QueryRunner();
            String sql = "delete from customers where id < ?";
            int update = queryRunner.update(connection, sql, 3);
            System.out.println("刪除了 " + update + " 條記錄");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection, null);
        }
    }

    // 修改記錄
    @Test
    public void testUpdate() {
        Connection connection = null;
        try {
            connection = JDBCUtils.getDruidConnection();

            QueryRunner queryRunner = new QueryRunner();
            String sql = "update customers set email = ? where name = ?";
            int update = queryRunner.update(connection, sql, "[email protected]", "勁兒");
            System.out.println("修改了 " + update + " 條記錄");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection, null);
        }
    }

    // 查詢一條記錄,BeanHandler
    @Test
    public void testQuery() {
        Connection connection = null;
        try {
            connection = JDBCUtils.getDruidConnection();

            QueryRunner queryRunner = new QueryRunner();
            String sql = "select id,name,email,birth from customers where id = ?";
            // BeanHandler 是 ResultSetHandler 的實現類,用於封裝表中的一條記錄
            BeanHandler<Customer> handler = new BeanHandler<>(Customer.class);
            Customer customer = queryRunner.query(connection, sql, handler, 23);
            System.out.println(customer);   // Customer{id=23, name='勁兒', email='[email protected]', birth=1995-12-29}
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection, null);
        }
    }

    // 查詢一條記錄,MapHandler
    @Test
    public void testQueryMap() {
        Connection connection = null;
        try {
            connection = JDBCUtils.getDruidConnection();

            QueryRunner queryRunner = new QueryRunner();
            String sql = "select id,name,email,birth from customers where id = ?";
            MapHandler mapHandler = new MapHandler();
            Map<String, Object> map = queryRunner.query(connection, sql, mapHandler, 23);
            System.out.println(map);    // {name=勁兒, birth=1995-12-29, id=23, [email protected]}
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection, null);
        }
    }

    // 查詢多條記錄,BeanListHandler
    @Test
    public void testQueryList() {
        Connection connection = null;
        try {
            connection = JDBCUtils.getDruidConnection();

            QueryRunner queryRunner = new QueryRunner();
            String sql = "select id,name,email,birth from customers where id < ?";
            BeanListHandler<Customer> listHandler = new BeanListHandler<>(Customer.class);
            List<Customer> customerList = queryRunner.query(connection, sql, listHandler, 13);
            customerList.forEach(System.out::println);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection, null);
        }
    }

    // 查詢多條記錄,MapListHandler
    @Test
    public void testQueryMapList() {
        Connection connection = null;
        try {
            connection = JDBCUtils.getDruidConnection();

            QueryRunner queryRunner = new QueryRunner();
            String sql = "select id,name,email,birth from customers where id < ?";
            MapListHandler mapListHandler = new MapListHandler();
            List<Map<String, Object>> mapList = queryRunner.query(connection, sql, mapListHandler, 13);
            mapList.forEach(System.out::println);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection, null);
        }
    }

    // 查詢特殊值,類似於最大的,最小的,平均的,總和,個數相關的資料,ScalarHandler
    @Test
    public void testQueryScalar() {
        Connection connection = null;
        try {
            connection = JDBCUtils.getDruidConnection();

            QueryRunner queryRunner = new QueryRunner();

            String sql = "select count(*) from customers where id < ?";
            ScalarHandler scalarHandler = new ScalarHandler();
            Object query = queryRunner.query(connection, sql, scalarHandler, 20);
            System.out.println(query);

            String sql1 = "select max(birth) from customers";
            ScalarHandler handler = new ScalarHandler();
            Object query1 = queryRunner.query(connection, sql1, handler);
            System.out.println(query1);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection, null);
        }
    }


}

練習和總結