1. 程式人生 > >DBCP和Druid資料庫連線池使用

DBCP和Druid資料庫連線池使用

需要用到的jar包,commons-dbcp2-*.jar、commons-logging-*.jar、commons-pool2-*.jar,*代表版本號

DataSourceTest類

package com.edu.zzu.Util;

import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.sql.DataSource;
import
java.sql.Connection; import java.sql.SQLException; import java.util.Properties; public class DataSourceTest { private static final Log log = LogFactory.getLog(DataSourceTest.class); private static final String configFile = "dbcp.properties"; private static DataSource dataSource; static
{ Properties properties = new Properties(); try { properties.load(DataSourceTest.class.getClassLoader().getResourceAsStream(configFile)); dataSource = BasicDataSourceFactory.createDataSource(properties); } catch (Exception e) { log.error("初始化連線池失敗:"
+e); } } public static Connection getConnection() { try { return dataSource.getConnection(); } catch (SQLException e) { log.error("獲取資料庫連線失敗:"+e); } return null; } public static void close(Connection conn) { try{ if (conn != null || !conn.isClosed()) { conn.setAutoCommit(true); conn.close(); } } catch (Exception e) { } } }

dbcp.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/lecture
username=root
password=123456
initialSize=10
maxActive=50
maxIdle=10
maxWait=10

DruidPool

package com.edu.zzu.Util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidPool {
    private static DataSource dataSource;
    static {
        Properties prop = new Properties();
        try {
            prop.load(DataBaseConnection.class.getClassLoader().getResourceAsStream("dbcp.properties"));
        } catch (IOException e) {
            System.out.println("資料庫配置檔案丟失");
            e.printStackTrace();
        }
        try {
            dataSource = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}