dbcp开源连接池的使用例子

来源:互联网 发布:jymusic源码 编辑:程序博客网 时间:2024/03/29 18:34

第一:使用dbcp必须先导入这两个jar包:

commons-dbcp-1.4.jar 和 commons-pool-1.5.6.jar

下载地址:

http://download.csdn.net/download/qqahanson/8212045


使用列子:

src 文件

import java.io.FileInputStream;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.Properties;import javax.sql.DataSource;import org.apache.commons.dbcp.BasicDataSource;import org.apache.commons.dbcp.BasicDataSourceFactory;import org.junit.Test;public class Demo1Dbcp {@Test// DBCP入门案例public void test() throws Exception {//创建DBCD数据源BasicDataSource dataSource = new BasicDataSource();//配置数据源的基本信息dataSource.setDriverClassName("com.mysql.jdbc.Driver");dataSource.setUrl("jdbc:mysql:///jdbc");dataSource.setUsername("root");dataSource.setPassword("123456");//其实返回的是真实conn的一个代理对象,其中的close方法已经被改变Connection conn = dataSource.getConnection();PreparedStatement ps = conn.prepareStatement("select * from account");ResultSet rs = ps.executeQuery();while(rs.next()){String name = rs.getString("name");System.out.println(name);}rs.close();ps.close();//根据之前讲的原理,此处的close方法没有真的关闭连接,而是把连接还回到了池中conn.close();}@Test//利用配置文件配置DBCPpublic void test2() throws Exception{String path = this.getClass().getClassLoader().getResource("dbcp.properties").getPath();Properties prop = new Properties();prop.load(new FileInputStream(path));DataSource dataSource = BasicDataSourceFactory.createDataSource(prop);//其实返回的是真实conn的一个代理对象,其中的close方法已经被改变Connection conn = dataSource.getConnection();PreparedStatement ps = conn.prepareStatement("select * from account");ResultSet rs = ps.executeQuery();while(rs.next()){String name = rs.getString("name");System.out.println(name);}rs.close();ps.close();//根据之前讲的原理,此处的close方法没有真的关闭连接,而是把连接还回到了池中conn.close();}}

dbcp配置文件 dbcp.properties

driverClassName=com.mysql.jdbc.Driverurl=jdbc\:mysql\:///jdbcusername=rootpassword=123456


dbcp.properties 可配置模板:

#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb
username=root
password=root

#<!-- 初始化连接 -->
dataSource.initialSize=10

#<!-- 最大空闲连接 -->
dataSource.maxIdle=20

#<!-- 最小空闲连接 -->
dataSource.minIdle=5

#最大连接数量
dataSource.maxActive=50

#是否在自动回收超时连接的时候打印连接的超时错误
dataSource.logAbandoned=true

#是否自动回收超时连接
dataSource.removeAbandoned=true

#超时时间(以秒数为单位)
#设置超时时间有一个要注意的地方,超时时间=现在的时间-程序中创建Connection的时间,如果maxActive比较大,比如超过100,那么removeAbandonedTimeout可以设置长一点比如180,也就是三分钟无响应的连接进行回收,当然应用的不同设置长度也不同。
dataSource.removeAbandonedTimeout=180

#<!-- 超时等待时间以毫秒为单位 -->
#maxWait代表当Connection用尽了,多久之后进行回收丢失连接
dataSource.maxWait=1000



0 0
原创粉丝点击