日期:2014-05-18 浏览次数:20762 次
package com.yongan.pool;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class TestPool {
private static ComboPooledDataSource datasource;
private static TestPool instance;
/*
* 初始化数据库连接
*/
private TestPool(){
datasource = new ComboPooledDataSource();
try {
datasource.setUser("root");
datasource.setPassword("123456");
datasource.setJdbcUrl("jdbc:mysql://localhost/traffic");
datasource.setDriverClass("org.gjt.mm.mysql.Driver");
datasource.setInitialPoolSize(5);
datasource.setMinPoolSize(1);
datasource.setMaxPoolSize(10);
datasource.setMaxIdleTime(60);
datasource.setMaxStatements(50);
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static TestPool getManagerConnection(){
if(instance == null){
instance = new TestPool();
}
return instance;
}
public static Connection getConnection(){
Connection con = null;
try {
con = datasource.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
public static Connection getNotPoolConnection(){
Connection con = null;
try {
Class.forName("org.gjt.mm.mysql.Driver");
String url = "jdbc:mysql://localhost/traffic";
String user = "root";
String password = "123456";
con = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
public static void main(String[] args) {
System.out.println("不使用线程池");
for(int i=0 ; i< 10 ; i++){
long beginTime = System.currentTimeMillis();
Connection con = TestPool.getNotPoolConnection();
try{
PreparedStatement pst = con.prepareStatement("select * from tb_action");
ResultSet rs = pst.executeQuery();
while(rs.next()){
}
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.p