1.DBCP简介
DBCP(DataBase connection pool)数据库连接池是 apache 上的一个Java连接池项目。DBCP通过连接池预先同数据库建立一些连接放在内存中(即连接池中),应用程序需要建立数据库连接时直接到从接池中申请一个连接使用,用完后由连接池回收该连接,从而达到连接复用,减少资源消耗的目的。
2.DBCP依赖的jar包
commons-dbcp2-2.1.1.jar commons-logging-1.2.jar commons-pool2-2.4.2.jar
点击下载
3.采用properties文件配置dbcp
properties文件采用的是key=value形式储存的,通过**getProperty(key)**获取value值
properties工具类
public class PropertiesUtil {
public static String getProperties(String key,String filename){
Properties p = new Properties();
InputStream is = null;
String property = null;
try {
is = PropertiesUtil.class.getClassLoader().getResourceAsStream(filename);//创建输入流
p.load(is);//加载输入流
property = p.getProperty(key);//利用key获取value
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
is.close();
}
return property;
}
public static void setProperties(String key,String value,String filename){
Properties p = new Properties();
String path = null;
try {
path = URLDecoder.decode(PropertiesUtil.class.getClassLoader().getResource(filename).getPath(),"utf-8");url解码
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(path,true);
p.setProperty(key, value);//设置值
p.store(fos, "123");//设置备注
} catch (IOException e) {
e.printStackTrace();
}finally{
fos.close();
}
}
}
配置连接池
public class Dbcp {
private static Dbcp dbcp;
private static BasicDataSource bdSource;
static{
bdSource = new BasicDataSource();
String filename = "jdbc.properties";
bdSource.setUsername(PropertiesUtil.getProperties("user", filename));//数据库用户名
bdSource.setPassword(PropertiesUtil.getProperties("password", filename));//密码
bdSource.setUrl(PropertiesUtil.getProperties("url", filename));//url地址
bdSource.setDriverClassName(PropertiesUtil.getProperties("driver", filename));//驱动名
bdSource.setMinIdle(Integer.valueOf(PropertiesUtil.getProperties("minIdle", filename)));最小连接数
bdSource.setMaxIdle(Integer.valueOf(PropertiesUtil.getProperties("maxIdle", filename)));最大连接数
bdSource.setInitialSize(Integer.valueOf(PropertiesUtil.getProperties("initialSize", filename)));初始化连接数
bdSource.setMaxWaitMillis(Integer.valueOf(PropertiesUtil.getProperties("maxWaitMillis", filename)));最大等待时间
}
public static Connection getConnection(){//提供连接
Connection conn = null;
try {
conn = bdSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}