DBCP和Druid数据库连接池使用

时间:2021-05-22 08:27:44

需要用到的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;
}
}