用Commons组件的DBCP构建简单的连接池
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
/**
* 数据库连接池,使用Commons组件的dbcp实现
* @author Kaka
*
*/
public class DBConnectionPool {
private static BasicDataSource dataSource = null;
public synchronized static void init() {
System.out.println("-----setInitialSize");
if(dataSource!=null)
return;
Properties p=null;
try {
p = MySql.getProperties();
dataSource = (BasicDataSource) BasicDataSourceFactory
.createDataSource(p);
dataSource.setInitialSize(20);
} catch (Exception e) {
e.printStackTrace();
}finally{
}
}
public static Connection getConnection() throws SQLException {
if (dataSource == null) {
init();
}
return dataSource.getConnection();
}
public static void main(String[] args) throws SQLException {
//测试代码
/*
long start=System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
Connection conn=null;
conn=getConnection();
conn.close();
}
long end=System.currentTimeMillis();
System.out.println(end-start);
long start1=System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
Connection conn=null;
conn=MySql.getConnectionClear();
conn.close();
}
long end1=System.currentTimeMillis();
System.out.println(end1-start1);
*/
}
}
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
/**
* 数据库连接池,使用Commons组件的dbcp实现
* @author Kaka
*
*/
public class DBConnectionPool {
private static BasicDataSource dataSource = null;
public synchronized static void init() {
System.out.println("-----setInitialSize");
if(dataSource!=null)
return;
Properties p=null;
try {
p = MySql.getProperties();
dataSource = (BasicDataSource) BasicDataSourceFactory
.createDataSource(p);
dataSource.setInitialSize(20);
} catch (Exception e) {
e.printStackTrace();
}finally{
}
}
public static Connection getConnection() throws SQLException {
if (dataSource == null) {
init();
}
return dataSource.getConnection();
}
public static void main(String[] args) throws SQLException {
//测试代码
/*
long start=System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
Connection conn=null;
conn=getConnection();
conn.close();
}
long end=System.currentTimeMillis();
System.out.println(end-start);
long start1=System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
Connection conn=null;
conn=MySql.getConnectionClear();
conn.close();
}
long end1=System.currentTimeMillis();
System.out.println(end1-start1);
*/
}
}