1. 程式人生 > >Druid 連線池 JDBCUtils 工具類的使用

Druid 連線池 JDBCUtils 工具類的使用

Druid工具介紹

它不僅僅是一個數據庫連線池,它還包含一個ProxyDriver,一系列內建的JDBC元件庫,一個SQL Parser。 支援所有JDBC相容的資料庫,包括Oracle、MySQL、Derby、Postgresql、SQL Server、H2等等。 Druid針對oracle和mysql做了特別優化,比如Oracle的PS Cache記憶體佔用優化,MySql的ping檢測優化。Druid提供了MySql、Oracle、Postgresql、SQL-92的SQL的完整支援,這是一個手寫的高效能SQL Parser,支援Visitor模式,使得分析SQL的抽象語法樹很方便。簡單SQL語句用時10微秒以內,複雜SQL用時30微秒。 
通過Druid提供的SQL Parser可以在JDBC層攔截SQL做相應處理,比如說分庫分表、審計等。Druid防禦SQL注入攻擊的WallFilter就是通過Druid的SQL Parser分析語義實現的 

效能上圖示分析

這個圖示是從別人的blog上面copy過了 ,這個是sql語句進行1000次以後的查詢提醒druid 連線池的效能分析,大家可以做為參考,是否準確待定。。

這裡寫圖片描述

工具的使用

這個是在程式碼中去註冊一些配置資訊,不常用的 大家隨便看看就好

package com.ruirui.druid;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.junit.Test;

import com.alibaba.druid
.pool.DruidDataSource; import com.ruirui.decoratedesgin.Utils; public class DruidDemo { @Test public void druidTest(){ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName
("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql:///stu"); dataSource.setUsername("root"); dataSource.setPassword("123456"); try{ // 獲得連線: conn = dataSource.getConnection(); // 編寫SQL: String sql = "select * from student"; pstmt = conn.prepareStatement(sql); // 執行sql: rs = pstmt.executeQuery(); while(rs.next()){ System.out.println(rs.getInt("id")+" "+rs.getString("name")); } }catch(Exception e){ e.printStackTrace(); }finally{ Utils.releaseResouce(rs, ps tmt, conn); } } }

註冊資訊在配置檔案中

@Test
    public void demo2(){
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try{
            Properties properties = new Properties();
            properties.load(new FileInputStream("src/druid.properties"));
            DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
            // 獲得連線:
            conn = dataSource.getConnection();
            // 編寫SQL:
            String sql = "select * from account";
            pstmt = conn.prepareStatement(sql);
            // 執行sql:
            rs = pstmt.executeQuery();
            while(rs.next()){
                System.out.println(rs.getInt("id")+"   "+rs.getString("name")+"   "+rs.getDouble("money"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            JDBCUtils.release(rs, pstmt, conn);
        }
    }

配置檔案

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///day04
username=root
password=123

這裡配置資訊有很多 最大連線數量 , 最小連線數量等。。。配置的資訊很多啊 大家可以去讀一下官方文件。。 跟C3P0使用的情況 基本上都差不多

> 這裡是下載地址druid 文件 jar包  http://pan.baidu.com/s/1jHYEPpk

C3P0介紹

簡介

目前使用C3P0連線池的開源專案有hibernate,spring等,其實所有的連線池都是為了提高應用於資料庫自己的訪問效率,資源管理等問題,使用的方法還有原理也不會有太大差別

示例程式碼

// 配置檔案的方式

    public void demo2(){

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try{

            // 核心類:
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
            // 獲得連線:
            conn = dataSource.getConnection();

            // 編寫SQL:
            String sql = "select * from account";
            pstmt = conn.prepareStatement(sql);
            // 執行sql:

            rs = pstmt.executeQuery();

            while(rs.next()){

                System.out.println(rs.getInt("id")
        }

        }catch(Exception e){

            e.printStackTrace();

        }finally{

            JDBCUtils.release(rs, pstmt, conn);

        }       
    }

配置檔案資訊

<?xml version="1.0" encoding="UTF-8"?>
 <c3p0-config> 
     <default-config> 
         <property name="driverClass">com.mysql.jdbc.Driver</property> 
         <property name="jdbcUrl">jdbc:mysql:///day04</property> 
         <property name="user">root</property> 
         <property name="password">123</property> 
         <property name="minPoolSize">5</property> 
         <property name="initialPoolSize">5</property> 
     </default-config>
         <named-config name="oracle"> 
         <property name="driverClass">com.mysql.jdbc.Driver</property> 
         <property name="jdbcUrl">jdbc:mysql:///day04</property> 
         <property name="user">root</property> 
         <property name="password">123</property> 
         <property name="minPoolSize">5</property> 
         <property name="initialPoolSize">5</property> 
     </named-config>
</c3p0-config>

如果要ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("oracle"); 表示的是使用下面的配置檔案資訊,如果沒有找到oracle的話就會使用上圖模式配置資訊

JDBCUtils工具類的使用

package com.ruirui.jdbcutils;

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

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.KeyedHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JDBCUtils {
    /**
     *   QueryRunner:核心執行類
     *   ResultSetHandler:提供對查詢結果封裝
     *   DbUtils    :工具類
     */

    //c3p0 連線池
    public DataSource comboPooledDataSource = new ComboPooledDataSource();

    public Connection getConn() throws SQLException{

        return comboPooledDataSource.getConnection();
    }

    //插入資料
    public void saveData() throws SQLException {

        QueryRunner queryRunner = new QueryRunner(comboPooledDataSource);

        String sql = "insert into student values(null,'ruirui',?,?);";

        queryRunner.update(sql, "shenyang",27);
    }

    // 修改表

    public void fixData() throws SQLException{

        QueryRunner queryRunner = new QueryRunner(comboPooledDataSource);
        String sql = "update student set name=? where id=?;";
        queryRunner.update(sql,"pp", 13);
    }


    // 刪除操作
    public void demo3() throws SQLException{
        QueryRunner queryRunner = new QueryRunner(comboPooledDataSource);
        String sql ="delete from account where id =?";
        queryRunner.update(sql, 4);
    }


    // ArrayHandler:將查詢到的一條記錄封裝到陣列當中
    public void demo1() throws SQLException{
        QueryRunner queryRunner = new QueryRunner(comboPooledDataSource);
        String sql  = "select * from account where id = ?";
        Object[] objs = queryRunner.query(sql, new ArrayHandler(), 1); // ”1“ 代表一條資料
        System.out.println(Arrays.toString(objs));
    }

    //ArrayListHandler 
    //一條查詢是ArrayHandler 一個數組
    //多條查詢 就是將多個數組 存入集合中
    public void demo2() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(comboPooledDataSource);
        String sql  = "select * from student";

        List<Object[]> query = queryRunner.query(sql, new ArrayListHandler());

        for (Object[] objects : query) {

            for (Object object : objects) {
                System.out.println(object.toString());
            }
        }
    }

    //查詢一條記錄 返回的是一個bean物件
    public void demo4() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(comboPooledDataSource);
        String sql  = "select * from student where id = ?";
        Man man = queryRunner.query(sql, new BeanHandler<>(Man.class),5);
        System.out.println(man.toString());
    }

    //注意返回的是一個標準的javabean物件,所在定義bean物件時候成員變數必須用private定義

    //查詢一條記錄 返回的是一個bean物件
    public void demo5() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(comboPooledDataSource);
        String sql  = "select * from student";
        List<Man> query = queryRunner.query(sql, new BeanListHandler<>(Man.class ));
        System.out.println(query.toString());
    }

    // MapHandler:封裝一條記錄到Map中
    public void demo6()throws SQLException{
        QueryRunner queryRunner = new QueryRunner(comboPooledDataSource);
        String sql = "select * from student where id = ?";
        Map<String,Object> map = queryRunner.query(sql, new MapHandler() ,2);
        System.out.println(map);
    } 

    // MapListHandler: //查詢多條 將map集合存入list 集合中
    public void demo7()throws SQLException{
        QueryRunner queryRunner = new QueryRunner(comboPooledDataSource);
        String sql = "select * from student";
        List<Map<String,Object>> list = queryRunner.query(sql, new MapListHandler());
        for (Map<String, Object> map : list) {
            System.out.println(map);
        }
    }

    // ColumnListHandler ,返回的是一個列值的集合
    public void demo8()throws SQLException{
        QueryRunner queryRunner = new QueryRunner(comboPooledDataSource);
        String sql = "select id from student";
        List<Object> list  = queryRunner.query(sql, new ColumnListHandler());
        for (Object object : list) {
            System.out.println(object.toString());
        }
    }

    //ScalarHandler:單值查詢
    public void demo9()throws SQLException{
        QueryRunner queryRunner = new QueryRunner(comboPooledDataSource);
        String sql = "select sum(age) from student;";
        Long count = (Long)queryRunner.query(sql, new ScalarHandler());
        System.out.println(count);
    }
    @Test
    // KeyedHandler:
    public void demo10()throws SQLException{
        QueryRunner queryRunner = new QueryRunner(comboPooledDataSource);
        String sql = "select * from student";
        Map<Object,Map<String,Object>> map= queryRunner.query(sql, new KeyedHandler("name"));
        for (Object key : map.keySet()) {
            System.out.println(key + "   "+map.get(key));
        }
    }

}

JDBUtils 文件以及jar 下載連結