Dbcp数据库连接池
Dbcp是apache的产品
下载包地址:http://commons.apache.org/proper/commons-pool/download_pool.cgi
根据自身jdk版本下载合适的包
需要导的包:commons-dbcp-1.4.jar commons-pool-1.6.jar
Dbcp有两种获得Connection的方法:1.BasicDataSource 2.BasicDataSourceFactory
先来看看BasicDataSource
需要配置文件 Properties
db.properties 文件内容如下:
url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
user = root
password = 123123
forname = com.mysql.jdbc.Driver
public class Dbcp {
private static String url = null;
private static String user = null;
private static String password = null;
private static String driverClassName = null;
public static BasicDataSource ds = null;
static {
Properties prop = new Properties();
InputStream inputStream = Dbcp.class.getResourceAsStream("/propp.properties");
try {
prop.load(inputStream);
//从配置文件获得 url
url = prop.getProperty("url");
//从配置文件获得连接名 user
user = prop.getProperty("user");
password = prop.getProperty("password");
//连接驱动
driverClassName = prop.getProperty("forname");
try {
Class.forName(driverClassName).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//创建对象
ds = new BasicDataSource();
//把从配置文件获得的值设置给BasicDataSource
ds.setUrl(url);
ds.setUsername(user);
ds.setPassword(password);
ds.setDriverClassName(driverClassName);
//设置初始化大小
ds.setInitialSize(5);
//设置最大连接数
ds.setMaxActive(10);
//设置超过最大数等待时间
ds.setMaxWait(3000);
} catch (IOException e) {
e.printStackTrace();
}
}
//获得一个Connection连接
public static Connection getCon() {
try {
return ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//简易打印测试
public static void main(String[] args) {
for(int i=0; i<15; i++) {
System.out.println(getCon());
}
}
}
相对于BasicDataSource,BasicDataSourceFactory就更简洁一点了
配置文件不变
public class Dbcp2 {
public static BasicDataSource ds = null;
static {
Properties prop = new Properties();
InputStream inputStream = Dbcp2.class.getResourceAsStream("/db.properties");
try {
prop.load(inputStream);
//直接把配置文件对象传入
//需要注意的是,配置文件的字段命名方式必须要和BasicDataSource 提供的方法对应
//比如:ds.setUrl(url); 字段就应为url
ds = (BasicDataSource) BasicDataSourceFactory.createDataSource(prop);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getCon() {
try {
return ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
for(int i=0; i<8; i++) {
System.out.println(getCon());
}
}
}