天天看點

mysql連接配接池_資料庫技術:資料庫連接配接池,Commons DbUtils,批處理,中繼資料

mysql連接配接池_資料庫技術:資料庫連接配接池,Commons DbUtils,批處理,中繼資料

Database Connection Pool

Introduction to Database Connection Pool

實際開發中“獲得連接配接”或“釋放資源”是非常消耗系統資源的兩個過程,為了解決此類性能問題,通常情況我們采用連接配接池技術,來共享連接配接 Connection。這樣我們就不需要每次都建立連接配接、釋放連接配接了,因為這些操作都交給了連接配接池。

連接配接池的好處:使用池來管理 Connection,這樣可以重複使用 Connection。當使用完 Connection 後,調用 Connection 的 close() 方法也不會真的關閉 Connection,而是把 Connection “歸還”給池。

How to Use Database Connection Pool?

Java 為資料庫連接配接池提供了公共的接口:

javax.sql.DataSource

,各個廠商需要讓自己的連接配接池實作這個接口,這樣應用程式可以友善的切換不同廠商的連接配接池。

常見的連接配接池有 DBCP 連接配接池,C3P0 連接配接池,Druid 連接配接池。

想了解更多,歡迎關注我的微信公衆号:Renda_Zhang

Data Preparation

在 MySQL 中準備好以下資料

# 建立資料庫
CREATE DATABASE db5 CHARACTER SET utf8;
 
# 使用資料庫
USE db5;
 
# 建立員工表
CREATE TABLE employee (
    eid INT PRIMARY KEY AUTO_INCREMENT,
    ename VARCHAR (20), -- 員工姓名
    age INT,            -- 員工年齡
    sex VARCHAR (6),    -- 員工性别
    salary DOUBLE,      -- 薪水
    empdate DATE        -- 入職日期
);
 
# 插入資料
INSERT INTO employee (eid, ename, age, sex, salary, empdate) VALUES(NULL,'李清照',22,'女',4000,'2018-11-12');
INSERT INTO employee (eid, ename, age, sex, salary, empdate) VALUES(NULL,'林黛玉',20,'女',5000,'2019-03-14');
INSERT INTO employee (eid, ename, age, sex, salary, empdate) VALUES(NULL,'杜甫',40,'男',6000,'2020-01-01');
INSERT INTO employee (eid, ename, age, sex, salary, empdate) VALUES(NULL,'李白',25,'男',3000,'2017-10-01');
           

DBCP 連接配接池

DBCP 是一個開源的連接配接池,是 Apache 成員之一,在企業開發中比較常見,Tomcat 内置的連接配接池。

建立項目并導入 jar包

首先将

commons-dbcp

commons-pool

兩個 jar 包添加到

myJar

檔案夾中,然後添加

myJar

庫到項目的依賴中。

編寫工具類

連接配接資料庫表的工具類,采用 DBCP 連接配接池的方式來完成。

在 DBCP 包中提供了

DataSource

接口的實作類,我們要用的具體的連接配接池

BasicDataSource

類。

public class DBCPUtils {
    // 定義常量 儲存資料庫連接配接的相關資訊
    public static final String DRIVERNAME = "com.mysql.jdbc.Driver";
    public static final String URL = "jdbc:mysql://localhost:3306/db5?characterEncoding=UTF-8";
    public static final String USERNAME = "root";
    public static final String PASSWORD = "root";

    // 建立連接配接池對象 (有 DBCP 提供的實作類)
    public static BasicDataSource dataSource = new BasicDataSource();

    // 使用靜态代碼塊進行配置
    static{
        dataSource.setDriverClassName(DRIVERNAME);
        dataSource.setUrl(URL);
        dataSource.setUsername(USERNAME);
        dataSource.setPassword(PASSWORD);
    }

    // 擷取連接配接的方法
    public static Connection getConnection() throws SQLException {
        // 從連接配接池中擷取連接配接
        Connection connection = dataSource.getConnection();
        return connection;
    }

    // 釋放資源方法

    public static void close(Connection con, Statement statement){
        if(con != null && statement != null){
            try {
                statement.close();
                // 歸還連接配接
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    public static void close(Connection con, Statement statement, ResultSet resultSet){
        if(con != null && statement != null && resultSet != null){
            try {
                resultSet.close();
                statement.close();
                // 歸還連接配接
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
           

測試工具類

/*
 * 查詢所有員工的姓名
 **/
public class TestDBCP {
    public static void main(String[] args) throws SQLException {
        // 從 DBCP 連接配接池中拿到連接配接
        Connection con = DBCPUtils.getConnection();

        // 擷取 Statement 對象
        Statement statement = con.createStatement();

        // 查詢所有員工的姓名
        String sql = "select ename from employee";
        ResultSet resultSet = statement.executeQuery(sql);

        // 處理結果集
        while(resultSet.next()){
            String ename = resultSet.getString("ename");
            System.out.println("員工姓名: " + ename);
        }

        // 釋放資源
        DBCPUtils.close(con, statement, resultSet);
    }
}
           

C3P0 連接配接池

C3P0 是一個開源的 JDBC 連接配接池,支援 JDBC 3 規範和 JDBC 2 的标準擴充。目前使用它的開源項目有 Hibernate、Spring 等。

導入 jar 包及配置檔案

首先将

c3p0

mchange-commons-java

兩個 jar 包複制到

myJar

檔案夾即可,IDEA 會自動導入。

然後導入配置檔案

c3p0-config.xml

c3p0-config.xml

檔案名不可更改,可以直接放到

src

下,也可以放到到資源檔案夾中。

最後在項目下建立一個 resource 檔案夾(專門存放資源檔案),将配置檔案放在 resource 目錄下即可,建立連接配接池對象的時候會自動加載這個配置檔案。

<c3p0-config>

    <!--預設配置-->
    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/db5?characterEncoding=UTF-8</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <!-- initialPoolSize:初始化時擷取三個連接配接,取值在 minPoolSize 與 maxPoolSize 之間。-->
        <property name="initialPoolSize">3</property>
        <!-- maxIdleTime:最大空閑時間,60 秒内未使用則連接配接被丢棄。若為 0 則永不丢棄。-->
        <property name="maxIdleTime">60</property>
        <!-- maxPoolSize:連接配接池中保留的最大連接配接數 -->
        <property name="maxPoolSize">100</property>
        <!-- minPoolSize: 連接配接池中保留的最小連接配接數 -->
        <property name="minPoolSize">10</property>
    </default-config>

    <!--配置連接配接池 mysql-->
    <named-config name="mysql">
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/db5</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="initialPoolSize">10</property>
        <property name="maxIdleTime">30</property>
        <property name="maxPoolSize">100</property>
        <property name="minPoolSize">10</property>
    </named-config>

    <!--可以配置多個連接配接池-->

</c3p0-config>
           

編寫 C3P0 工具類

C3P0 提供的核心工具類

ComboPooledDataSource

,如果想使用連接配接池,就必須建立該類的對象。

使用預設配置:

new ComboPooledDataSource();

使用命名配置:

new ComboPooledDataSource("mysql");

public class C3P0Utils {
    // 使用指定的配置
    public static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql");

    // 擷取連接配接的方法
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    // 釋放資源

    public static void close(Connection con, Statement statement){
        if(con != null && statement != null){
            try {
                statement.close();
                // 歸還連接配接
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection con, Statement statement, ResultSet resultSet){
        if(con != null && statement != null && resultSet != null){
            try {
                resultSet.close();
                statement.close();
                // 歸還連接配接
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}
           

測試工具類

// 查詢姓名為李白的記錄
public class TestC3P0 {
    public static void main(String[] args) throws SQLException {
        // 擷取連接配接
        Connection con = C3P0Utils.getConnection();

        // 擷取預處理對象
        String sql = "select * from employee where ename = ?";
        PreparedStatement ps = con.prepareStatement(sql);

        // 設定占位符的值
        ps.setString(1,"李白");
        ResultSet resultSet = ps.executeQuery();

        // 處理結果集
        while (resultSet.next()){
            int eid = resultSet.getInt("eid");
            String ename = resultSet.getString("ename");
            int age = resultSet.getInt("age");
            String sex = resultSet.getString("sex");
            double salary = resultSet.getDouble("salary");
            Date date = resultSet.getDate("empdate");
            System.out.println(eid+" "+ename+" "+age+" "+sex+" "+salary+" "+date);
        }

        // 釋放資源
        C3P0Utils.close(con, ps, resultSet);
    }
}
           

Druid 連接配接池

Druid(德魯伊)是阿裡巴巴開發的為監控而生的資料庫連接配接池,Druid 是目前最好的資料庫連接配接池。在功能、性能、擴充性方面,都超過其他資料庫連接配接池,同時加入了日志監控,可以很好的監控 DB 池連接配接和 SQL 的執行情況。

導入 jar 包及配置檔案

首先導入

druid

jar 包。然後導入 properties 配置檔案,可以叫任意名稱,可以放在任意目錄下,但是這裡統一放到 resources 資源目錄。

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/db5?characterEncoding=UTF-8
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000
           

編寫 Druid 工具類

通過工廠來來擷取

DruidDataSourceFactory

類的

createDataSource(Properties p)

方法,其參數可以是一個屬性集對象。

public class DruidUtils {

    // 定義成員變量
    public static DataSource dataSource;

    // 靜态代碼塊
    static{
        try {
            // 建立屬性集對象
            Properties p = new Properties();
            // 加載配置檔案 Druid 連接配接池不能夠主動加載配置檔案,需要指定檔案
            InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            // 使用 Properties 對象的 load 方法從位元組流中讀取配置資訊
            p.load(inputStream);
            // 通過工廠類擷取連接配接池對象
            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 擷取連接配接的方法
    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 釋放資源

    public static void close(Connection con, Statement statement){
        if(con != null && statement != null){
            try {
                statement.close();
                // 歸還連接配接
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    public static void close(Connection con, Statement statement, ResultSet resultSet){
        if(con != null && statement != null && resultSet != null){
            try {
                resultSet.close();
                statement.close();
                // 歸還連接配接
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
           

測試工具類

// 查詢薪資在 3000 - 5000 元之間的員工姓名
public class TestDruid {
    public static void main(String[] args) throws SQLException {
        // 擷取連接配接
        Connection con = DruidUtils.getConnection();

        // 擷取 Statement 對象
        Statement statement = con.createStatement();

        // 執行查詢
        ResultSet resultSet = statement.executeQuery("select ename from employee where salary between 3000 and 5000");

        // 處理結果集
        while(resultSet.next()){
            String ename = resultSet.getString("ename");
            System.out.println(ename);
        }

        // 釋放資源
        DruidUtils.close(con,statement,resultSet);
    }
}
           

Commons DbUtils

Introduction to

DbUtils

Commons DbUtils

是 Apache 組織提供的一個對 JDBC 進行簡單封裝的開源工具類庫,使用它能夠簡化 JDBC 應用程式的開發,同時也不會影響程式的性能。

DbUtils

就是 JDBC 的簡化開發工具包,需要在項目導入

commons-dbutils

jar 包。

DbUtils

核心功能:

  1. QueryRunner

    中提供對 SQL 語句操作的 API。
  2. ResultSetHandler

    接口用于定義 select 操作後封裝結果集。
  3. DbUtils

    類是一個定義了關閉資源與事務處理相關方法的工具類。

相關知識

表和類之間的關系

整個表可以看做是一個類。

表中的一列,對應類中的一個成員屬性。

表中的一行記錄,對應一個類的執行個體(對象)。

JavaBean 元件

JavaBean 是一個開發中通常用于封裝資料的類:

  1. 需要實作序列化接口,Serializable(暫時可以省略)
  2. 提供私有字段:private 類型變量名
  3. 提供 getter 和 setter
  4. 提供空參構造

建立一個 entity 包,專門用來存放 JavaBean 類,然後在 entity 包中建立一個和資料庫的 Employee 表對應的 Employee 類。

public class Employee implements Serializable {
    private int eid;
    private String ename;
    private int age;
    private String  sex;
    private double salary;
    private Date empdate;
    // getter setter
    ...
}
           

Use

DbUtils

for CRUD Operations

QueryRunner

的建立

手動模式

// 建立 QueryRunner 對象
QueryRunner qr = new QueryRunner();
           

自動模式

// 傳入資料庫連接配接池對象
QueryRunner qr2 = new QueryRunner(DruidUtils.getDataSource());
           

自動模式需要傳入連接配接池對象

// 擷取連接配接池對象
public static DataSource getDataSource(){
    return dataSource;
}
           

QueryRunner

實作增、删、改操作

步驟:

  1. 建立

    QueryRunner

    (手動或自動)
  2. 占位符方式編寫SQL
  3. 設定占位符參數
  4. 執行

添加:

@Test
public void testInsert() throws SQLException {
    // 手動模式建立 QueryRunner
    QueryRunner qr = new QueryRunner();

    // 編寫占位符方式 SQL
    String sql = "insert into employee values(?,?,?,?,?,?)";

    // 設定占位符的參數
    Object[] param = {null,"布萊爾",20,"女",10000,"1990-12-26"};

    // 執行 update 方法
    Connection con = DruidUtils.getConnection();
    int i = qr.update(con, sql, param);

    // 釋放資源
    DbUtils.closeQuietly(con);
}
           

修改:

@Test
public void testUpdate() throws SQLException {
    // 自動模式建立 QueryRunner 對象,傳入資料庫連接配接池
    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

    // 編寫 SQL
    String sql = "update employee set salary = ? where ename = ?";

    // 設定占位符參數
    Object[] param = {0, "布萊爾"};

    // 執行 update,不需要傳入連接配接對象
    qr.update(sql, param);
}
           

删除:

@Test
public void testDelete() throws SQLException {
    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

    String sql = "delete from employee where eid = ?";

    //隻有一個參數,不需要建立數組
    qr.update(sql, 1);
}
           

QueryRunner

實作查詢操作

ResultSetHandler

可以對查詢出來的

ResultSet

結果集進行處理,達到一些業務上的需求。

query

方法的傳回值都是泛型,具體的傳回值類型會根據結果集的處理方式發生變化。

query(String sql, ResultSetHandler rsh, Object[] param)

-- 自動模式建立

QueryRunner

, 執行查詢。

query(Connection con, String sql, ResultSetHandler rsh, Object[] param)

-- 手動模式建立

QueryRunner

, 執行查詢。

/*
 * 查詢 id 為 5 的記錄,封裝到數組中
 *
 * ArrayHandler:
 * 将結果集的第一條資料封裝到 Object[] 數組中,
 * 數組中的每一個元素就是這條記錄中的每一個字段的值
 **/
@Test
public void testFindById() throws SQLException {
    // 建立 QueryRunner
    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

    // 編寫 SQL
    String sql = "select * from employee where eid = ?";

    // 執行查詢
    Object[] query = qr.query(sql, new ArrayHandler(), 5);

    // 擷取資料
    System.out.println(Arrays.toString(query));
}
/**
 * 查詢所有資料,封裝到 List 集合中
 *
 * ArrayListHandler:
 * 可以将每條資料先封裝到 Object[] 數組中,
 * 再将數組封裝到集合中
 */
@Test
public void testFindAll() throws SQLException {

    //1.建立QueryRunner
    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

    //2.編寫SQL
    String sql = "select * from employee";

    //3.執行查詢
    List<Object[]> query = qr.query(sql, new ArrayListHandler());

    //4.周遊集合擷取資料
    for (Object[] objects : query) {
        System.out.println(Arrays.toString(objects));
    }
}
/**
 * 查詢 id 為 3 的記錄,封裝到指定 JavaBean 中
 *
 * BeanHandler:
 * 将結果集的第一條資料封裝到 JavaBean 中
 **/
@Test
public void testFindByIdJavaBean() throws SQLException {

    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

    String sql = "select * from employee where eid = ?";

    Employee employee = qr.query(sql, new BeanHandler<Employee>(Employee.class), 3);

    System.out.println(employee);
}
/*
 * 查詢薪資大于 3000 的所員工資訊,
 * 封裝到 JavaBean 中再封裝到 List 集合中
 *
 * BeanListHandler:
 * 将結果集的每一條和資料封裝到 JavaBean 中,
 * 再将 JavaBean 放到 List 集合中
 * */
@Test
public void testFindBySalary() throws SQLException {
    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

    String sql = "select * from employee where salary > ?";

    List<Employee> list = qr.query(sql, new BeanListHandler<Employee>(Employee.class), 3000);

    for (Employee employee : list) {
        System.out.println(employee);
    }
}
/*
 * 查詢姓名是布萊爾的員工資訊,
 * 将結果封裝到 Map 集合中
 *
 * MapHandler:
 * 将結果集的第一條記錄封裝到 Map 中,
 * key 對應的是列名,
 * value 對應的是列的值
 **/
@Test
public void testFindByName() throws SQLException {
    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

    String sql = "select * from employee where ename = ?";

    Map<String, Object> map = qr.query(sql, new MapHandler(), "布萊爾");

    Set<Map.Entry<String, Object>> entries = map.entrySet();
    for (Map.Entry<String, Object> entry : entries) {
        System.out.println(entry.getKey() +" = " +entry.getValue());
    }
}
/*
 * 查詢所有員工的薪資總額
 *
 * ScalarHandler:
 * 用于封裝單個的資料
 **/
@Test
public void testGetSum() throws SQLException {
    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

    String sql = "select sum(salary) from employee";

    Double sum = (Double) qr.query(sql, new ScalarHandler<>());

    System.out.println("員工薪資總額: " + sum);
}
           

Database Batch Process

What is Database Batch Process?

批處理操作資料庫:批處理指的是一次操作中執行多條 SQL 語句,批處理相比于一次一次執行效率會提高很多。當向資料庫中添加大量的資料時,需要用到批處理。

Implement Batch Processing

Statement

PreparedStatement

都支援批處理操作。

MySQL

批處理是預設關閉的,是以需要加一個參數才打開

MySQL

資料庫批處理,在

url

中添加

rewriteBatchedStatements=true

url=jdbc:mysql://127.0.0.1:3306/db5?characterEncoding=UTF-8&rewriteBatchedStatements=true
           

建立一張表

CREATE TABLE testBatch (
    id INT PRIMARY KEY AUTO_INCREMENT,
    uname VARCHAR(50)
)
           

測試向表中插入一萬條資料

public class TestBatch {
    public static void main(String[] args) {
        try {
            // 擷取連接配接
            Connection con = DruidUtils.getConnection();

            // 擷取預處理對象
            String sql ="insert into testBatch(uname) values(?)";
            PreparedStatement ps = con.prepareStatement(sql);

            // 建立 for 循環來設定占位符參數
            for (int i = 0; i < 10000 ; i++) {
                ps.setString(1, "小明"+i);
                // 将 SQL 添加到批處理清單
                ps.addBatch();
            }

            long start = System.currentTimeMillis();

            // 統一批量執行
            ps.executeBatch();
            
            long end = System.currentTimeMillis();
            System.out.println("插入10000條資料使用: "+(end-start)+" 毫秒!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
           

MySQL Metadata

What is Metadata in MySQL

除了表之外的資料都是中繼資料,可以分為三類:

  1. 查詢結果資訊,UPDATE 或 DELETE語句 受影響的記錄數。
  2. 資料庫和資料表的資訊,包含了資料庫及資料表的結構資訊。
  3. MySQL伺服器信,包含了資料庫伺服器的目前狀态,版本号等。

常用指令

select version();

擷取 MySQL 伺服器的版本資訊

show status;

檢視伺服器的狀态資訊

show columns from table_name;

顯示表的字段資訊等,和

desc table_name

一樣

show index from table_name;

顯示資料表的詳細索引資訊,包括主鍵

show databases:

列出所有資料庫

show tables;

顯示目前資料庫的所有表

select database();

擷取目前的資料庫名

使用 JDBC 擷取中繼資料

通過 JDBC 也可以擷取到中繼資料,比如,資料庫的相關資訊,或者,使用程式查詢一個不熟悉的表時,可以通過擷取元素據資訊來了解表中有多少個字段、字段的名稱、字段的類型。

DatabaseMetaData

描述資料庫的中繼資料對象

ResultSetMetaData

描述結果集的中繼資料對象

public class TestMetaData {

    // 擷取資料庫相關的中繼資料資訊
    @Test
    public void testDataBaseMetaData() throws SQLException {
        Connection connection = DruidUtils.getConnection();

        // 擷取代表資料庫的中繼資料對象
        DatabaseMetaData metaData = connection.getMetaData();

        // 擷取資料庫相關的中繼資料資訊
        String url = metaData.getURL();
        System.out.println("資料庫URL: " + url);
        String userName = metaData.getUserName();
        System.out.println("目前使用者: " + userName );
        String productName = metaData.getDatabaseProductName();
        System.out.println("資料庫産品名: " + productName);
        String version = metaData.getDatabaseProductVersion();
        System.out.println("資料庫版本: " + version);
        String driverName = metaData.getDriverName();
        System.out.println("驅動名稱: " + driverName);

        // 判斷目前資料庫是否隻允許隻讀
        boolean b = metaData.isReadOnly();
        if(b){
            System.out.println("目前資料庫隻允許讀操作!");
        }else{
            System.out.println("不是隻讀資料庫");
        }

        connection.close();
    }

    // 擷取結果集中的中繼資料資訊
    @Test
    public void testResultSetMetaData() throws SQLException {
        Connection con = DruidUtils.getConnection();
        PreparedStatement ps = con.prepareStatement("select * from employee");
        ResultSet resultSet = ps.executeQuery();

        // 擷取結果集元素據對象
        ResultSetMetaData metaData = ps.getMetaData();

        // 擷取目前結果集共有多少列
        int count = metaData.getColumnCount();
        System.out.println("目前結果集中共有: "+count+"列");

        // 獲結果集中列的名稱和類型
        for (int i = 1; i <=  count; i++) {
            String columnName = metaData.getColumnName(i);
            System.out.println("列名: "+columnName);

            String columnTypeName = metaData.getColumnTypeName(i);
            System.out.println("類型: "+columnTypeName);
        }

        DruidUtils.close(con, ps, resultSet);
    }
}
           

繼續閱讀