通过DBCP连接池获取数据库连接
DBCP依赖三个jar包
- commons-dbcp2-2.1.1.jar
- commons-logging-1.2.jar
- commons-pool2-2.4.2.jar
参考配置文件
########DBCP配置文件##########
#驱动名
driverClassName=com.mysql.jdbc.Driver
#url
url=jdbc:mysql://127.0.0.1:3306/mydb
#用户名
username=sa
#密码
password=123456
#初试连接数
initialSize=30
#最大活跃数
maxTotal=30
#最大idle数
maxIdle=10
#最小idle数
minIdle=5
#最长等待时间(毫秒)
maxWaitMillis=1000
#程序中的连接不使用后是否被连接池回收(该版本要使用removeAbandonedOnMaintenance和removeAbandonedOnBorrow)
#removeAbandoned=true
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true
#连接在所指定的秒数内未使用才会被删除(秒)(为配合测试程序才配置为1秒)
removeAbandonedTimeout=1
通过DBCP获取数据库连接
private static DataSource dataSource = null;
//加载dbcp.properties配置文件
static {
try {
Properties properties = new Properties();
InputStream is = JDBCTools.class.getClassLoader().getResourceAsStream("dbcp.properties");
properties.load(is);
dataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws Exception {
return dataSource.getConnection();
}