dbcp需要3个包:common-dbcp.jar,common-pool.jar,common-collections.jar
package com.www.dbcp;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
public class DbcpConnection {
private static DataSource ds;
private static Connection conn;
public static void initDataSource(){
FileInputStream is = null;
Properties pps = new Properties();
String drc = null;
String url = null;
String username = null;
String password = null;
//连接池启动时创建的初始化连接数量(默认值为0)
int initialSize =0;
//连接池中最大的空闲的连接数,超过的空闲连接将被释放,如果设置为负数表示不限制(默认为8个
int maxIdle = 0;
//连接池中最小的空闲的连接数,低于这个数量会被创建新的连接
int minIdle = 0;
//最大等待时间,当没有可用连接时,连接池等待连接释放的最大时间,超过该时间限制会抛出异常
int maxWait = 0;
//:连接池中可同时连接的最大的连接数
int maxActive = 0;
String path = “E:\\WorkSpace\\javareback\\src\\com\\www\\dbcp\\dbcp.properties”;
try {
is = new FileInputStream(path);
pps.load(is);
drc = pps.getProperty(“driverClassName”);
url = pps.getProperty(“url”);
username = pps.getProperty(“username”);
password = pps.getProperty(“password”);
initialSize = Integer.parseInt((pps.getProperty(“initialSize”).trim()));
minIdle = Integer.parseInt((pps.getProperty(“minIdle”)).trim());
maxIdle = Integer.parseInt((pps.getProperty(“maxIdle”)).trim());
maxWait = Integer.parseInt((pps.getProperty(“maxWait”)).trim());
maxActive = Integer.parseInt((pps.getProperty(“maxActive”)).trim());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
BasicDataSource bds = new BasicDataSource();
bds.setUrl(url);
bds.setDriverClassName(drc);
bds.setUsername(username);
bds.setPassword(password);
bds.setInitialSize(initialSize);
//bds.setMaxA(maxActive);
bds.setMinIdle(minIdle);
bds.setMaxIdle(maxIdle);
bds.setMaxWaitMillis(maxWait);
ds = bds;
}
public static Connection getConnection() throws SQLException{
if(ds == null){
initDataSource();
}
Connection conn = null;
if(ds != null){
conn = ds.getConnection();
}
return conn;
}
}
dbcp.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mytest
username=root
password=root123
initialSize=10
minIdle=10
maxIdle=10
maxWait=10000
maxActive=30