原來不知道使用c3p0 是如此的簡單,我一直使用properties文件去配置c3p0,但總是連接不上數(shù)據(jù)庫,后來調(diào)試才發(fā)現(xiàn)ComboPooledDataSource這個對象的屬性沒有被設(shè)置成功,我是先獲取了properties文件的內(nèi)容,封裝在一個 Properties對象里面,然后直接調(diào)用ComboPooledDataSource 的 setProperties(Properties p)方法來配置c3p0,程序是沒有報錯,但連不上數(shù)據(jù)庫,調(diào)試發(fā)現(xiàn)屬性都沒有設(shè)置成功,只是properties這個屬性被設(shè)置了而已,結(jié)果我對每個屬性調(diào)用set方法后就連接上了。。。
public final class ConnectionManager {
private static ConnectionManager instance;
public ComboPooledDataSource ds;
private static String c3p0Properties ="c3p0.properties";
private ConnectionManager() throws Exception{
Properties p = newProperties();
p.load(this.getClass().getResourceAsStream(c3p0Properties));
ds = newComboPooledDataSource();
ds.setUser(p.getProperty("user"));
ds.setPassword(p.getProperty("user"));
ds.setJdbcUrl(p.getProperty("user"));
ds.setDriverClass(p.getProperty("user"));
ds.setInitialPoolSize(Integer.parseInt(p.getProperty("initialPoolSize")));
ds.setMinPoolSize(Integer.parseInt(p.getProperty("minPoolSize")));
ds.setMaxPoolSize(Integer.parseInt(p.getProperty("maxPoolSize")));
ds.setMaxStatements(Integer.parseInt(p.getProperty("maxStatements")));
ds.setMaxIdleTime(Integer.parseInt(p.getProperty("maxIdleTime")));
}
public static final ConnectionManagergetInstance() {
if (instance == null){
try{
instance= new ConnectionManager();
} catch(Exception e) {
e.printStackTrace();
}
}
return instance;
}
public synchronized final ConnectiongetConnection() {
try {
returnds.getConnection();
} catch (SQLException e){
e.printStackTrace();
}
return null;
}
protected void finalize() throws Throwable{
DataSources.destroy(ds); //關(guān)閉datasource
super.finalize();
}
}
如此就可以獲取connection來做jdbc操作了:
Connectionconn=ConnectionManager.getInstance().getConnection();
記得使用完后調(diào)用close方法:
conn.close();
c3p0 的某些參數(shù)的配置以及意義見另外一篇文章http://kangzye.blog.163.com/blog/static/368192232010442162576/