package com.risencn.util;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DBUtilOfC3P0 {
private static ComboPooledDataSource dataSource;
private static DBUtilOfC3P0 instance = null;
public String driver = "oracle.jdbc.driver.OracleDriver";
public String url = "jdbc:oracle:thin:@localhost:1521:orcl";
public String username = "scott";
public String password = "tiger";
private DBUtilOfC3P0() {
dataSource = new ComboPooledDataSource(); // 設定jdbc連接配接資訊
dataSource.setUser(username);
dataSource.setPassword(password);
dataSource.setJdbcUrl(url);
try {
dataSource.setDriverClass(driver);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
// 設定連接配接池
dataSource.setInitialPoolSize(30);
dataSource.setMaxPoolSize(100);
dataSource.setMinPoolSize(10);
}
// 為了保證單例性,必須使用同步關鍵字
public synchronized static DBUtilOfC3P0 getInstance() {
if (instance == null)
instance = new DBUtilOfC3P0();
return instance;
}
// 連接配接必要的資訊
public Connection getConnection() throws SQLException { // 使用工廠建立連接配接
return dataSource.getConnection();
}
//測試
public static void main(String[] args) throws SQLException {
long begin = System.currentTimeMillis();
// 開始時刻
for(int i=0;i<1000;i++){//獲得1000次連接配接
Connection conn = DBUtilOfC3P0.getInstance().getConnection();
conn.close();
}
long end = System.currentTimeMillis();
System.out.println("C3P0連接配接資料庫所需要的時 間:"+(end-begin));
// //在我的機子上1000次C3P0連接配接耗時:656毫秒
}
}