JDBC笔记-DBCP连接池的简单使用

通过DBCP连接池获取数据库连接

DBCP依赖三个jar包

  • commons-dbcp2-2.1.1.jar
  • commons-logging-1.2.jar
  • commons-pool2-2.4.2.jar

参考配置文件

########DBCP配置文件##########
#驱动名
driverClassName=com.mysql.jdbc.Driver
#url
url=jdbc:mysql://127.0.0.1:3306/mydb
#用户名
username=sa
#密码
password=123456
#初试连接数
initialSize=30
#最大活跃数
maxTotal=30
#最大idle数
maxIdle=10
#最小idle数
minIdle=5
#最长等待时间(毫秒)
maxWaitMillis=1000
#程序中的连接不使用后是否被连接池回收(该版本要使用removeAbandonedOnMaintenance和removeAbandonedOnBorrow)
#removeAbandoned=true
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true
#连接在所指定的秒数内未使用才会被删除(秒)(为配合测试程序才配置为1秒)
removeAbandonedTimeout=1

通过DBCP获取数据库连接

private static DataSource dataSource = null;
//加载dbcp.properties配置文件
static {
	try {
		Properties properties = new Properties();
		InputStream is = JDBCTools.class.getClassLoader().getResourceAsStream("dbcp.properties");
		properties.load(is);
		dataSource = BasicDataSourceFactory.createDataSource(properties);
	} catch (IOException e) {
		e.printStackTrace();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
	
public static Connection getConnection() throws Exception {
	return dataSource.getConnection();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值