JavaJDBC【六、连接池】
背景
1、连接是一种重要资源
2、频繁连接数据库会增加数据库压力
常用连接池
dbcp
1、导入jar包(官网下载)
commons-dbcp.jar
commons-pool.jar
commons-logging.jar
2、配置
dbcp.properties
![](http://images2015.cnblogs.com/blog/692906/201704/692906-20170406081212363-330328016.png)
3、用配置创建DataSource
Properties p = new Properties();
p.load(Object.class.getResourceAsStream("fileName");
DataSource ds = BasicDataSourceFactory.createDataSource(p);
4、用DataSource获取连接
Connection con = ds.getConnection();
Demo:
public class DBCPUtil {
private static DataSource DS;
private static final String config = "/dbcp.properties";
public DBCPUtil() {
initDBCP();
}
private static void initDBCP() {
Properties ppts = new Properties();
try {
ppts.load(Object.class.getResourceAsStream(config));
DS = BasicDataSourceFactory.createDataSource(ppts);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public Connection GetConnection() {
Connection con = null;
try {
if (DS != null) {
con = DS.getConnection();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
c3p0
1、导入jar包(官网下载)
c3p0.jar
mchange-commons.jar
2、配置
c3p0.properties![](http://images2015.cnblogs.com/blog/692906/201704/692906-20170407082502113-1572894078.png)
3、创建DataSource
ComboPooledDataSource DS = new ComboPooledDataSource();
4、用DataSource获取连接
Connection con = DS.getConnection();
Demo:
public class C3P0Util {
private static ComboPooledDataSource DS = new ComboPooledDataSource();
public static Connection GetConnection() throws SQLException {
Connection con = DS.getConnection();
return con;
}
}