需要下commons-dbcp commons-pool 这两个jar包
import org.apache.commons.dbcp.basicdatasource;
import org.apache.commons.dbcp.basicdatasourcefactory;
import java.sql.connection;
import java.util.properties;
public class connectionsource {
private static basicdatasource datasource = null;
public connectionsource() {
}
public static void init() {
if (datasource != null) {
try {
datasource.close();
} catch (exception e) {
//
datasource = null;
properties p = new properties();
p.setproperty("url", "jdbc:oracle:thin:@192.168.0.1:1521:testdb");
p.setproperty("password", "scott");
p.setproperty("username", "tiger");
p.setproperty("maxactive", "30");
p.setproperty("maxidle", "10");
p.setproperty("maxwait", "1000");
p.setproperty("removeabandoned", "false");
p.setproperty("removeabandonedtimeout", "120");
p.setproperty("testonborrow", "true");
p.setproperty("logabandoned", "true");
datasource = (basicdatasource) basicdatasourcefactory.createdatasource(p);
public static synchronized connection getconnection() throws sqlexception {
if (datasource == null) {
init();
connection conn = null;
conn = datasource.getconnection();
return conn;
在使用properties来创建basicdatasource时,有很多参数可以设置,比较重要的还有:
还有2个参数:timebetweenevictionrunsmillis 和 minevictableidletimemillis, 他们两个配合,可以持续更新连接池中的连接对象,当timebetweenevictionrunsmillis 大于0时,每过timebetweenevictionrunsmillis 时间,就会启动一个线程,校验连接池中闲置时间超过minevictableidletimemillis的连接对象。
最新内容请见作者的github页:http://qaseven.github.io/