1. 程式人生 > 實用技巧 >資料庫連線池

資料庫連線池

我們在使用資料庫連線的時候一般是不會讓我們去手動實現jdbc去連線資料庫的,不,是一定。因為jdbc不停的去建立關閉連線是很耗費資源的,所以就有了資料庫連線池

資料庫連線池

概念:其實就是一個容器(集合),存放資料庫連線的容器。
        當系統初始化好後,容器被建立,容器中會申請一些連線物件,當用戶來訪問資料庫時,從容器中獲取連線物件,使用者訪問完之後,會將連線物件歸還給容器。

資源池的優點:

    1. 節約資源
    2. 使用者訪問高效

資料庫連線池分類:

有很多種 我們來舉例兩個 免費的:
    C3P0:資料庫連線池技術 --- 可以省略一本不會去使用



    Druid:資料庫連線池實現技術,由阿里巴巴提供的  
---主要使用這個

Druid :使用步驟

1: 首先匯入 Druid的jar包 :druid-1.0.9.jar

2. 定義配置檔案:
            * 是properties形式的
            * 可以叫任意名稱,可以放在任意目錄下
        3. 載入配置檔案。Properties
        4. 獲取資料庫連線池物件:通過工廠來來獲取  DruidDataSourceFactory
        5. 獲取連線:getConnection

資料庫連線池的close()

資料庫連線池的close()是歸還連線,將從資料庫連線池獲取的連線歸還到池內不是關閉資料庫連線

eg:

配置檔案.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///girls
username=zhao
password=123456
# 初始化連線數量
initialSize=5
# 最大連線數
maxActive=10
# 最大等待時間
maxWait=3000

定義工具類獲取配置檔案建立連線

    public static DataSource source;
    static {
        try {
            Properties pro = new Properties();
            InputStream 
is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties"); // 載入配置檔案 pro.load(is); source = DruidDataSourceFactory.createDataSource(pro); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnectionOne() throws SQLException { Connection conn = source.getConnection(); return conn; }

使用

    public void Update(){
        Connection conn = null;
        PreparedStatement state = null;
        try {
            conn = JdbcPool.getConnectionOne();  -- 使用資料庫連線池獲取連線
            String sql = "update admin set username =? where password =?";
            state = conn.prepareStatement(sql);
            state.setObject(1,"AugustFive");
            state.setObject(2,"500");
            state.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if(state != null){
                try {
                    state.close();  釋放連線 將連線歸還到資料庫連線池內
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

Apache-DBUtils

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

Spring Jdbc

spring-beans-5.0.0.RELEASE-sources.jar
spring-core-5.0.0.RELEASE-sources.jar
spring-jdbc-5.0.0.RELEASE-sources.jar
spring-tx-5.0.0.RELEASE-sources.jar
commons-logging-1.2.jar

這五個jar包的匯入

* 步驟:
    1. 匯入jar包
    2. 建立JdbcTemplate物件。依賴於資料來源DataSource
        * JdbcTemplate template = new JdbcTemplate(ds);

    3. 呼叫JdbcTemplate的方法來完成CRUD的操作
        * update():執行DML語句。增、刪、改語句
        * queryForMap():查詢結果將結果集封裝為map集合,將列名作為key,將值作為value 將這條記錄封裝為一個map集合
            * 注意:這個方法查詢的結果集長度只能是1
        * queryForList():查詢結果將結果集封裝為list集合
            * 注意:將每一條記錄封裝為一個Map集合,再將Map集合裝載到List集合中
        * query():查詢結果,將結果封裝為JavaBean物件
            * query的引數:RowMapper
                * 一般我們使用BeanPropertyRowMapper實現類。可以完成資料到JavaBean的自動封裝
                * new BeanPropertyRowMapper<型別>(型別.class)
        * queryForObject:查詢結果,將結果封裝為物件
            * 一般用於聚合函式的查詢

//    Druid連線池的工具類

    private static DataSource source;
    static {
        try {
            Properties pro = new Properties();
            InputStream is  = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);
            source = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        Connection conn = source.getConnection();
        return  conn;
    }

    // 獲取連線池方法
    public static  DataSource getSource(){
        return source;
    }
DruidUtils

package cn.itcast.jdbctemplate;

import cn.itcast.domain.Emp;
import cn.itcast.utils.JDBCUtils;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

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

public class JdbcTemplateDemo2 {

    //Junit單元測試,可以讓方法獨立執行


    //1. 獲取JDBCTemplate物件
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    /**
     * 1. 修改1號資料的 salary 為 10000
     */
    @Test
    public void test1(){

        //2. 定義sql
        String sql = "update emp set salary = 10000 where id = 1001";
        //3. 執行sql
        int count = template.update(sql);
        System.out.println(count);
    }

    /**
     * 2. 新增一條記錄
     */
    @Test
    public void test2(){
        String sql = "insert into emp(id,ename,dept_id) values(?,?,?)";
        int count = template.update(sql, 1015, "郭靖", 10);
        System.out.println(count);

    }

    /**
     * 3.刪除剛才新增的記錄
     */
    @Test
    public void test3(){
        String sql = "delete from emp where id = ?";
        int count = template.update(sql, 1015);
        System.out.println(count);
    }

    /**
     * 4.查詢id為1001的記錄,將其封裝為Map集合
     * 注意:這個方法查詢的結果集長度只能是1
     */
    @Test
    public void test4(){
        String sql = "select * from emp where id = ? or id = ?";
        Map<String, Object> map = template.queryForMap(sql, 1001,1002);
        System.out.println(map);
        //{id=1001, ename=孫悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20}

    }

    /**
     * 5. 查詢所有記錄,將其封裝為List
     */
    @Test
    public void test5(){
        String sql = "select * from emp";
        List<Map<String, Object>> list = template.queryForList(sql);

        for (Map<String, Object> stringObjectMap : list) {
            System.out.println(stringObjectMap);
        }
    }

    /**
     * 6. 查詢所有記錄,將其封裝為Emp物件的List集合
     */

    @Test
    public void test6(){
        String sql = "select * from emp";
        List<Emp> list = template.query(sql, new RowMapper<Emp>() {

            @Override
            public Emp mapRow(ResultSet rs, int i) throws SQLException {
                Emp emp = new Emp();
                int id = rs.getInt("id");
                String ename = rs.getString("ename");
                int job_id = rs.getInt("job_id");
                int mgr = rs.getInt("mgr");
                Date joindate = rs.getDate("joindate");
                double salary = rs.getDouble("salary");
                double bonus = rs.getDouble("bonus");
                int dept_id = rs.getInt("dept_id");

                emp.setId(id);
                emp.setEname(ename);
                emp.setJob_id(job_id);
                emp.setMgr(mgr);
                emp.setJoindate(joindate);
                emp.setSalary(salary);
                emp.setBonus(bonus);
                emp.setDept_id(dept_id);

                return emp;
            }
        });


        for (Emp emp : list) {
            System.out.println(emp);
        }
    }

    /**
     * 6. 查詢所有記錄,將其封裝為Emp物件的List集合
     */

    @Test
    public void test6_2(){
        String sql = "select * from emp";
        List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
        for (Emp emp : list) {
            System.out.println(emp);
        }
    }

    /**
     * 7. 查詢總記錄數
     */

    @Test
    public void test7(){
        String sql = "select count(id) from emp";
        Long total = template.queryForObject(sql, Long.class);
        System.out.println(total);
    }

}
使用

.