DBCP数据库连接池
DBCP(DataBase Connection Pool)
在开发项目时,需要不断的与数据库进行交互,java中使用JDBC连接数据库每次连接数据库都需要进行加载驱动,获取连接,销毁连接等步骤,耗时比较严重。为了解决这个问题,出现了数据库连接池技术。
DBCP是java数据库连接池的一种,由Apache开发。程序启动时,先创建一些数据库连接对象,只要需要连接数据库时就从对象池中获取一个对象,使用完成之后再返还给对象池。者样可以让程序自动管理数据库连接的释放和断开。
所需jar包:
commons-dbcp2-2.4.0,commons-logging-1.2,commons-pool2-2.6.1,mysql-connector-java-5.1.37-bin
链接:https://pan.baidu.com/s/120tXYYDtpAVveWOfKA8T8g
提取码:x5hi
步骤:
- 将上述jar包导入到项目中
- 新建dbcp.properties配置文件
########DBCP配置文件##########
#驱动名
driverClassName=com.mysql.jdbc.Driver
#url
url=jdbc:mysql://127.0.0.1:3306/数据库库名
#用户名
username=root
#密码
password=root
#初试连接数
initialSize=3
#最大活跃数
maxTotal=15
#最大idle数
maxIdle=15
#最小idle数
minIdle=3
#最长等待时间(毫秒)
maxWaitMillis=5000
#程序中的连接不使用后是否被连接池回收(该版本要使用removeAbandonedOnMaintenance和removeAbandonedOnBorrow)
#removeAbandoned=true
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true
#连接在所指定的秒数内未使用才会被删除(秒)(为配合测试程序才配置为1秒)
removeAbandonedTimeout=5
- 新建DBCPUtil.java工具类,部分代码如下
public class DBCPUtil {
private static Properties prop = new Properties();
private static DataSource dataSource;
static{
FileInputStream fis = null;
try {
//将dbcp.properties读入
fis = new FileInputStream("config/dbcp.properties");
//利用Properties集合将读到的配置文件载入内存中
prop.load(fis);
//创建dataSource
dataSource = BasicDataSourceFactory.createDataSource(prop);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(fis!=null){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static Connection getConnection(){
Connection conn = null;
try {
//获取数据库连接
dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
- 链接数据库工具类完成,使用JUnit4进行单元测试
//使用JUnit4:右键点击工程名 -> Bulid Path -> Add Liblraries -> JUnit
@Test
public void test(){
System.out.println(getConnection());
}
- 出现以下结果,说明连接成功