22Java之JDBCTemplate總結


寫在前面:這里總結4種方式來操作數據庫(SE階段)

一、JDBC

        JDBC有關的類:都在java.sql 和 javax.sql 包下.
 

        1.數據准備

                這里假設已經在數據庫中新建立了mydb4數據庫,並且也插入了一些數據,
                並且還需要導入一個jar包mysql-connector-java-8.0.11.jar(可從官網下載)

        2.JDBC 編程步驟

                步驟1:裝載驅動    DriverManager.registerDriver(new Driver());   
                            tips:在裝載驅動的時候推薦使用 Class.forName(“com.mysql.jdbc.Driver”);
                                     一、查看Driver的源代碼可以看到,如果采用此種方式,會導致驅動程序 注冊兩次,也就是在內存中會有兩個Driver對象。
                                     二、程序依賴mysql的api,脫離mysql的jar包,程序將無法編譯,將來程序切換底層數據庫將會非常麻煩。
                步驟2:建立連接    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb4", "root", "111");
                            tips:MySQL驅動 8 版本之后關於 driverClass 與 url 參數的書寫變化 :
com.mysql.cj.jdbc.Driver
jdbc:mysql://localhost:3306/day04?serverTimezone=UTC&characterEncoding=utf-8
 
                步驟3:操作數據庫
                                    Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
 System.out.println(rs.getString("username"));
 System.out.println(rs.getString("email"));
}
 
                步驟4:釋放資源

rs.close();

statement.close();

conn.close();

        3.一步到位的操作方式(更加面向對象&&解決SQL注入問題):

                    將重復的內容 提取到JDBCUtils工具類中:
                  
                    這里提供兩種版本分別是硬編碼和軟編碼
 
                    硬編碼(信息寫入到程序中):
JDBCUtils工具類
<wiz_code_mirror>
 
 
 
 
 
public class JDBCUtils {
 
    private static final String driverClass = "com.mysql.cj.jdbc.Driver";
    // 當時本地默認3306 可以省略,也可寫成 "jdbc:mysql://localhost:3306/mydb4?severTimezone=UTC&characterEncoding=utf-8"
    private static final String url = "jdbc:mysql:///mydb4?serverTimezone=UTC&character=utf-8";        
    private static final String user = "root";
    private static final String password = "111";
 
    // 加載驅動
    public static void loadDriver() {
        // 1. 加載驅動
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("驅動加載失敗!");
        }
    }
 
    // 獲取連接
    public static Connection getConnection() throws SQLException {
        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }
 
    // 釋放資源
    public static void release(Connection conn, Statement stmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            rs = null;
        }
        release(conn, stmt);
    }
 
    public static void release(Connection conn, Statement stmt) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            stmt = null;
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            conn = null;
        }
    }
}
 
 
測試類
<wiz_code_mirror>
 
 
 
 
 
    @Test
    public void test_query() {
        // 1. 加載驅動
        JDBCUtils.loadDriver();
 
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
 
        try {
            // 2. 建立連接
            conn = JDBCUtils.getConnection();
            // 3. 操作數據
            String sql = "select * from user;";
            // 這里有可能引起sql注入問題,換成prepareStatement(sql)
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            while (rs.next()) {
                String username = rs.getString("username");
                String password = rs.getString("password");
                System.out.println(username + " = " + password);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 4. 釋放資源
            JDBCUtils.release(conn, stmt, rs);
        }
    }
 
 
 
 
            軟編碼:從配置文件中讀取(配置文件名字jdbc.properties)
<wiz_code_mirror>
 
 
 
 
 
#配置文件
#jdbc.properties
#mysql
driverClass=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///mydb4?serverTimezone=UTC&character=utf-8
user=root
passwrod=111
 
 
<wiz_code_mirror>
 
 
 
 
 
public class JDBCUtils {
 
    // 屬性
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;
 
    // 請問 : 什么時候加載外部配置文件最合適 ???   
    // 特點1 : 隨着類的加載而加載.
    // 特點2 : 靜態代碼塊只在類加載的被執行一次. 僅一次.
    static {
        Properties prop = new Properties();
 
        try {
            prop.load(new FileReader("jdbc.properties")); // 這里直接放在項目的目錄下,具體要切合實際
 
            // 如果程序執行到這里, 說明外部資源文件加載成功, 需要給我們的靜態屬性賦值
            driverClass = prop.getProperty("driverClass");
            url = prop.getProperty("url");
            username = prop.getProperty("username");
            password = prop.getProperty("password");
 
            // 直接執行加載驅動
            loadDriver();
 
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("文件資源加載失敗!");
        }
    }
 
    // 加載驅動
    public static void loadDriver() {
        try {
            // 1. 加載驅動
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            // e.printStackTrace();
            // 驅動加載失敗!
            throw new RuntimeException("驅動加載失敗!");
        }
    }
 
    // 建立連接
    public static Connection getConnection() throws SQLException {
        // 2. 建立連接
        return DriverManager.getConnection(url, username, password);
    }
 
    // 釋放資源
    public static void release(Connection conn, Statement stmt, ResultSet rs) {
        // 4. 釋放資源
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            // 將 rs 清空
            rs = null;
        }
        // 直接調用
        release(conn, stmt);
    }
    public static void release(Connection conn, Statement stmt) {
        // 4. 釋放資源
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            stmt = null;
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            conn = null;
        }
    }
}
 
 
測試類:
<wiz_code_mirror>
 
 
 
 
 
    @Test
    public void test_query() {
 
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
 
        try {
            // 1. 建立連接
            conn = JDBCUtils.getConnection();
            // 2. 操作數據
            String sql = "select * from user where username = ? and password = ?;";
            // 預編譯sql
            stmt = conn.prepareStatement(sql);
            // 設置sql語句的參數
            stmt.setString(1, username);
            stmt.setString(2, password);
            // 執行sql語句
            rs = stmt.executeQuery();
            // 判斷返回的結果
            if (rs.next()) {
                // 登錄成功
                int id = rs.getInt("id");
                String u_name = rs.getString("username");
                String u_pwd = rs.getString("password");
                String email = rs.getString("email");
                System.out.println(id + " : " + u_name + " : " + u_pwd + " : " + email);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 3. 釋放資源
            JDBCUtils.release(conn, stmt, rs);
        }
    }
 
 
 
 
 
JDBCUtils中避免sql注入問題之后最終版總結:
                PreparedStatement的CRUD
<wiz_code_mirror>
 
 
 
 
 
    @Test
    public void test_update() {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            // 2. 建立連接
            conn = JDBCUtils.getConnection();
 
 // U 修改           
            // 3. 操作數據
            String sql = "update user set username = ?, password = ?, email = ? where id = ?;";
            stmt = conn.prepareStatement(sql);
            // 設置參數
            stmt.setString(1, "張三");
            stmt.setString(2, "888");
            stmt.setString(3, "zs@qiezi.cn");
            stmt.setInt(4, 1);
            // 執行
            int affectedRowNum = stmt.executeUpdate();
            System.out.println(affectedRowNum);
 
        
// 刪除
        
            // 2. 操作數據
            String sql = "delete from user where id = ?;";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, 4);
            int affectedRowNum = stmt.executeUpdate();
            System.out.println(affectedRowNum);
            
            
// 增加
            
            
            // 2. 操作數據
            String sql = "insert into user values(?,?,?,?);";
            stmt = conn.prepareStatement(sql);
            // 設置參數
            stmt.setInt(1, 4);
            stmt.setString(2, "趙六");
            stmt.setString(3, "888");
            stmt.setString(4, "zl@qiezi.cn");
            int affectedRowNumber = stmt.executeUpdate();
            System.out.println(affectedRowNumber);
        
        
            
// 查詢
            
            
                        // 2. 操作數據
            String sql = "select * from user where username = ? and password = ?;";
            stmt = conn.prepareStatement(sql);
            // 設置sql語句的參數
            stmt.setString(1, username);
            stmt.setString(2, password);
            // 執行sql語句
            rs = stmt.executeQuery();
            // 判斷返回的結果
            if (rs.next()) {
                // 登錄成功
                int id = rs.getInt("id");
                String u_name = rs.getString("username");
                String u_pwd = rs.getString("password");
                String email = rs.getString("email");
                System.out.println(id + " : " + u_name + " : " + u_pwd + " : " + email);
            }
        
        
    
        
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 4. 釋放資源
            JDBCUtils.release(conn, stmt);
        }
    }
 
 
 
 
 

二、JdbcTemplate

        

         JdbcTemplate 介紹

        JDBC已經能夠滿足大部分用戶最基本的需求,但是在使用JDBC時,必須自己來管理數據庫資源如:獲取PreparedStatement,設置SQL語句參數,關閉連接等步驟。JdbcTemplate就是Spring對JDBC的封裝,目的是使JDBC更加易於使用。JdbcTemplate是Spring的一部分
        JdbcTemplate處理了資源的建立和釋放。他幫助我們避免一些常見的錯誤,比如忘了總要關閉連接。他運行核心的JDBC工作流,如Statement的建立和執行,而我們只需要提供SQL語句和提取結果。
 
        在JdbcTemplate中執行SQL語句的方法大致分為3類:
1. execute:可以執行所有SQL語句,一般用於執行DDL語句。
2. update:用於執行INSERT、UPDATE、DELETE等DML語句。
3. queryXxx:用於DQL數據查詢語句。
********新增加,新復習
DDL (數據定義語言)
數據定義語言 - Data Definition Language
用來定義數據庫的對象,如數據表、視圖、索引等
create drop alter truncate
DML (數據操縱語言)
數據處理語言 - Data Manipulation Language
在數據庫表中更新,增加和刪除記錄
如 update, insert, delete 不包含查詢
DCL (數據控制語言)
數據控制語言 – Data Control Language
指用於設置用戶權限和控制事務語句
如grant,revoke,if…else,while,begin transaction
DQL (數據查詢語言)(★★★★★)
數據查詢語言 – Data Query Language
數據表記錄的查詢。
select
*********
 
 

           JDBCTemplate使用:

                         API介紹:
                            1.org.springframework.jdbc.core.JdbcTemplate類方便執行SQL語句
<wiz_code_mirror>
 
 
 
 
 
public JdbcTemplate(DataSource dataSource)
創建JdbcTemplate對象,方便執行SQL語句
public void execute(final String sql)
execute可以執行所有SQL語句,因為沒有返回值,一般用於執行DML語句。
public int update(final String sql)
用於執行`INSERT`、`UPDATE`、`DELETE`等DML語句。
public <T> T queryForObject(String sql, Class<T> requiredType, Object... args):
   傳入參數, 執行查詢語句,返回一個指定類型的數據。
   
   
   public Map<String, Object> queryForMap(String sql, Object... args)
傳入參數,執行查詢語句,將一條記錄放到一個Map中。
public List<Map<String, Object>> queryForList(String sql, Object... args)
傳入參數,執行查詢語句,返回一個List集合,List中存放的是Map類型的數據。
public <T> List<T> query(String sql, RowMapper<T> rowMapper)
執行查詢語句,返回一個List集合,List中存放的是RowMapper指定類型的數據。
public <T> List<T> query(String sql, RowMapper<T> rowMapper)
執行查詢語句,返回一個List集合,List中存放的是RowMapper指定類型的數據。
public class BeanPropertyRowMapper<T> implements RowMapper<T>
BeanPropertyRowMapper類實現了RowMapper接口
 
 
 
                        1.數據准備:
                                這里采用c3p0數據流連接池,集成到JDBCUtils 工具類中,需要將c3p0的配置文件放入到src目錄下
                                導入依賴的jar包
                                         - spring-beans-5.0.2.RELEASE.jar
- spring-core-5.0.2.RELEASE.jar
- spring-jdbc-5.0.2.RELEASE.jar
- spring-tx-5.0.2.RELEASE.jar
- com.springsource.org.apache.commons.logging-1.1.1.jar
                          2.創建JdbcTemplate對象,傳入c3p0連接池
                         3.調用 execute、update、queryXxx等方法
                             
c3p0-config.xml 配置文件
<wiz_code_mirror>
 
 
 
 
 
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <!-- 默認配置,c3p0框架默認加載這段默認配置 -->
    <default-config>
        <!-- 配置JDBC 四個基本屬性 -->
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb4?serverTimezone=UTC&amp;characterEncoding=utf-8</property>
        <property name="user">root</property>
        <property name="password">111</property>
    </default-config>
    <!-- 可以自定義配置,為這段配置起一個名字,c3p0指定名稱加載配置 -->
    <named-config name="zidingyimingzi">
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb4?serverTimezone=UTC&amp;characterEncoding=utf-8</property>
        <property name="user">root</property>
        <property name="password">111</property>
    </named-config>
</c3p0-config>
 
 
JDBCUtils 工具類
<wiz_code_mirror>
 
 
 
 
 
public class JDBCUtils {
    // 核心連接池類
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
    public static DataSource getDataSource() {
        return dataSource;
    }
    // 獲取連接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    // 釋放資源
    public static void release(Connection conn, Statement stmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            rs = null;
        }
        release(conn, stmt);
    }
    public static void release(Connection conn, Statement stmt) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            stmt = null;
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            conn = null;
        }
    }
}
 
 
測試類(實現增改)
<wiz_code_mirror>
 
 
 
 
 
public class JDBCTemplateExecute {
    public static void main(String[] args) {
 // 查詢語句
        
        
        
        // 1. 創建表的SQL語句
        String sql = "create table product (" +
                "pid int primary key auto_increment," +
                "pname varchar(20)," +
                "price double" +
                ");";
        // 2. 創建 jdbcTemplate 對象, 並將數據庫連接池作為參數傳入
        JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
        // 3. 使用 jdbcTemplate 對象調用 execute 方法, 執行 sql 語句, 創建數據庫表.
        jdbcTemplate.execute(sql);
        
        
        
// 增加數據
        
        // 2. 編寫 sql 語句
        String sql = "insert into product values(null, ?, ?);";
        // 3. 執行 update 方法.
        jdbcTemplate.update(sql, "iPhone3GS", 3333);
        jdbcTemplate.update(sql, "iPhone4", 5000);
        
        
        
 //   修改數據
        
        // 2. 執行 update 語句
        String sql = "update product set pname = ?, price = ? where pid = ?;";
        int count = jdbcTemplate.update(sql, "XVIII", 18888, 10);
        System.out.println("count = " + count);
        
     
// 刪除數據
        // 2. 執行 delete 操作
        String sql = "delete from product where pid = ?;";
        int count = jdbcTemplate.update(sql, 7);
        System.out.println("count = " + count);
    }
}
 
 
總結:JdbcTemplate的update方法用於執行DML語句。同時還可以在SQL語句中使用?占位,在update方法的Object... args可變參數中傳入對應的參數。
 
 
測試類(實現查詢)
<wiz_code_mirror>
 
 
 
 
 
    @Test
    public void test1() {
        // 1. 創建一個 JdbcTemplate 對象
        JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
        
        
//  queryForObject 方法
        
        
        // 2. 執行 queryForObject 方法
        String sql = "select pname from product where price = 7777";
        String pname = jdbcTemplate.queryForObject(sql, String.class);
        System.out.println("pname = " + pname);
        
     
        
// queryForMap 方法 
        
        // 2. 執行 queryForMap 方法
        String sql = "select * from product where pid = ?;";
        Map<String, Object> map = jdbcTemplate.queryForMap(sql, 6);
        System.out.println("map = " + map);
        
        
     
        
 // objectForList
        
        // 2. 執行 objectForList 方法
        String sql = "select * from product where pid < ?;";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, 8);
        for (Map<String, Object> map : list) {
            System.out.println(map);
        }
        
        
        
        
 // 使用RowMapper做映射返回對象
        
1. 定義Product類
2. 創建JdbcTemplate對象
3. 編寫查詢的SQL語句
4. 使用JdbcTemplate對象的query方法,並傳入RowMapper匿名內部類
5. 在匿名內部類中將結果集中的一行記錄轉成一個Product對象
        // 2. 執行 query 方法
        String sql = "select * from product;";
        List<Product> list = jdbcTemplate.query(sql, new RowMapper<Product>() {
            @Override
            public Product mapRow(ResultSet rs, int i) throws SQLException {
                Product product = new Product();
                int pid = rs.getInt("pid");
                String pname = rs.getString("pname");
                double price = rs.getDouble("price");
                product.setPid(pid);
                product.setPname(pname);
                product.setPrice(price);
                return product;
            }
        });
        // 遍歷 list 集合
        for (Product product : list) {
            System.out.println(product);
        }
1. 定義Product類
2. 創建JdbcTemplate對象
3. 編寫查詢的SQL語句
4. 使用JdbcTemplate對象的query方法,並傳入BeanPropertyRowMapper對象
         // 2. 執行 query 方法
        String sql = "select * from product;";
        List<Product> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Product.class));
        // 3. 遍歷 list 集合
        for (Product product : list) {
            System.out.println(product);
        }
    }
 
 
總結:
        JDBCTemplate的query方法用於執行SQL語句,簡化JDBC的代碼。同時還可以在SQL語句中使用?占位,在query方法的Object... args可變參數中傳入對應的參數。
 
 
三、c3p0
在Hibernate和Spring 都提供對C3P0連接池支持.
導入2個包
        c3p0-0.9.5.2.jar
        mchange-commons-java-0.2.11.jar
        mysql的jar包
        mysql-connector-java-8.0.11.jar
基本操作
          // 核心連接池類
  ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
  // 設置四個JDBC基本連接屬性
  comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
  comboPooledDataSource.setJdbcUrl("jdbc:mysql:///mydb4?serverTimezone=UTC&characterEnconding=utf-8");
  comboPooledDataSource.setUser("root");
  comboPooledDataSource.setPassword("111");
 
常用基本連接池屬性
    

acquireIncrement  如果連接池中連接都被使用了,一次性增長">3個新的連接

initialPoolSize  連接池中初始化連接數量默認:3

maxPoolSize      最大連接池中連接數量默認:15連接

maxIdleTime      如果連接長時間沒有時間,將被回收默認:0 連接永不過期

    minPoolSize      連接池中最小連接數量 默認:">3

通過c3p0創建數據庫連接池對象方式提取到JDBCUtils中
<wiz_code_mirror>
 
 
 
 
 
public class JDBCUtils {
 
    // c3p0 數據庫連接池對象屬性
    // 這里會自動讀取 位於src目錄下的c3p0-config.xml 數據庫連接池配置文件
    private static final ComboPooledDataSource dataSource = new ComboPooledDataSource();
 
    // 獲取連接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
 
    // 釋放資源
    public static void release(Connection conn, Statement stmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            rs = null;
        }
        release(conn, stmt);
    }
 
    public static void release(Connection conn, Statement stmt) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            stmt = null;
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            conn = null;
        }
    }
}
 
 
c3p0-config.xml 數據庫連接池配置文件 位於src 目錄下
<wiz_code_mirror>
 
 
 
 
 
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <!-- 默認配置,c3p0框架默認加載這段默認配置 -->
    <default-config>
        <!-- 配置JDBC 四個基本屬性 -->
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb4?serverTimezone=UTC&amp;characterEncoding=utf-8</property>
        <property name="user">root</property>
        <property name="password">111</property>
    </default-config>
    <!-- 可以自定義配置,為這段配置起一個名字,c3p0指定名稱加載配置 -->
    <named-config name="zidingyi">
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb4?serverTimezone=UTC&amp;characterEncoding=utf-8</property>
        <property name="user">root</property>
        <property name="password">111</property>
    </named-config>
</c3p0-config>
 
 
測試類:
<wiz_code_mirror>
 
 
 
 
 
    @Test
    public void test_jdbcUtils() {
 
        // 需求 : 查詢 user 表中的所有數據
 
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
 
        try {
            // 1. 建立連接
            conn = JDBCUtils.getConnection();
            // 2. 操作數據
            String sql = "select * from user;";
            stmt = conn.prepareStatement(sql);
            rs = stmt.executeQuery();
            while (rs.next()) {
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String password = rs.getString("password");
                String email = rs.getString("email");
                System.out.println(id + " : " + username + " : " + password + " : " + email);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 3. 釋放資源
            JDBCUtils.release(conn, stmt, rs);
        }
    }
 
 
 
 

四、druid

        Druid (德魯伊) 是阿里巴巴開發的號稱為監控而生的數據庫連接池,Druid是目前最好的數據庫連接池。在功能、性能、擴展性方面,都超過其他數據庫連接池,同時加入了日志監控,可以很好的監控DB池連接和SQL的執行情況。Druid已經在阿里巴巴部署了超過600個應用,經過一年多生產環境大規模部署的嚴苛考驗。Druid地址:https://github.com/alibaba/druid 
DRUID連接池使用的jar包:druid-1.0.9.jar
參數 說明
url 連接數據庫的url:jdbc:mysql://localhost:3306/mydb?serverTimezone=UTC&characterEncoding=utf-8
username 數據庫的用戶名
password 數據庫的密碼
driverClassName 驅動類名。根據url自動識別,這一項可配可不配,如果不配置druid會根據url自動識別dbType,然后選擇相應的driverClassName(建議配置下)
initialSize 初始化時建立物理連接的個數。初始化發生在顯示調用init方法,或者第一次getConnection時
maxActive 最大連接池數量
maxIdle 已經不再使用,配置了也沒效果
minIdle 最小連接池數量
maxWait 獲取連接時最大等待時間,單位毫秒。
 
        API介紹
 
                com.alibaba.druid.pool.DruidDataSourceFactory類有創建連接池的方法
 
<wiz_code_mirror>
 
 
 
 
 
public static DataSource createDataSource(Properties properties)
創建一個連接池,連接池的參數使用properties中的數據
 
 
tips:我們可以看到DRUID連接池在創建的時候需要一個Properties對象來設置參數,所以我們使用properties文件來保存對應的參數。
DRUID連接池的配置文件名稱隨便,因為該配置文件需要我們手動實現加載。
druid.properties文件內容:
<wiz_code_mirror>
 
 
 
 
 
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb?serverTimezone=UTC&characterEncoding=utf-8
username=root
password=111
  
  
initialSize=5
maxActive=10
maxWait=3000
maxIdle=6
minIdle=3
 
 
        使用步驟
1. 在src目錄下創建一個properties文件,並設置對應參數
2. 加載properties文件的內容到Properties對象中
3. 創建DRUID連接池,使用配置文件中的參數
4. 從DRUID連接池中取出連接
5. 執行SQL語句
6. 關閉資源
 
JDBCUtils 工具類集成 Druid 數據庫連接池
<wiz_code_mirror>
 
 
 
 
 
public class JDBCUtils {
    // 屬性
    private static final DataSource dataSource;
    static {
        Properties prop = new Properties();
        try {
            // 加載配置文件
            // 配置文件的位置無所謂,這里放的是項目的目錄下,因為Druid數據庫連接池需要手動加載配置文件
            prop.load(new FileReader("druid.properties"));
            // 創建數據庫連接池
            dataSource = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            throw new RuntimeException("連接池初始化失敗!");
        }
    }
    public static DataSource getDataSource() {
        return dataSource;
    }
    // 建立連接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    // 釋放資源
    public static void release(Connection conn, Statement stmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            rs = null;
        }
        release(conn, stmt);
    }
    public static void release(Connection conn, Statement stmt) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            stmt = null;
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                // e.printStackTrace();  ignore 忽略.
            }
            conn = null;    // 目的: 讓 conn 對象盡早被回收.
        }
    }
}
 
 
測試類:
 
<wiz_code_mirror>
 
 
 
 
 
    @Test
    public void test3() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            // 1. 建立連接
            conn = JDBCUtils.getConnection();
            // 2. 操作數據
            String sql = "select * from user;";
            stmt = conn.prepareStatement(sql);
            rs = stmt.executeQuery();
            while (rs.next()) {
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String password = rs.getString("password");
                String email = rs.getString("email");
                System.out.println(id + " : " + username + " : " + password + " : " + email);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 3. 釋放資源
            JDBCUtils.release(conn, stmt, rs);
        }
    }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
五、Hibernate
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
六、MyBatis


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM