c3p0很容易使用的開源專業(yè)級(jí)jdbc數(shù)據(jù)庫(kù)緩沖池。
它是sourceforge上的一個(gè)開源項(xiàng)目,
項(xiàng)目在
http://sourceforge.net/projects/c3p0
他的眾多特性這里就不一一介紹了。
比較爽的一點(diǎn)就是
當(dāng)Connection歸還緩沖池時(shí),c3p0會(huì)很小心的關(guān)閉
這條連接打開的Statement和ResultSet,免去了使用時(shí)
自己動(dòng)手小心翼翼的關(guān)閉。
c3p0使用非常簡(jiǎn)單,這里給一個(gè)例子
package common.db;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;
public final class ConnectionManager {
?private static ConnectionManager instance;
?
?public ComboPooledDataSource ds;
?private static String c3p0Properties="c3p0.properties";
?
?private ConnectionManager() throws Exception {
??Properties p = new Properties();
??p.load(this.getClass().getResourceAsStream(c3p0Properties));
??ds = new ComboPooledDataSource();
?}
?
?public static final ConnectionManager getInstance() {
??if (instance == null) {
???try {
????instance = new ConnectionManager();
???} catch (Exception e) {
????e.printStackTrace();
???}
??}
??return instance;
?}
?
?public synchronized final Connection getConnection() {
??try {
???return ds.getConnection();
??} catch (SQLException e) {
???e.printStackTrace();
??}
??return null;
?}
?protected void finalize() throws Throwable {
??DataSources.destroy(ds);?//關(guān)閉datasource
??super.finalize();
?}
?
}
然后在ConnectionManager類的目錄下再創(chuàng)建一個(gè)配置文件c3p0.properties
內(nèi)容如下:
#db login parameters
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost/test?useUnicode=no&characterEncoding=GBK
user=test
password=test
#pool parameters
initialPoolSize=2
maxPoolSize=5
#maxIdleTime=10
#idleConnectionTestPeriod=5
autoCommitOnClose=true
完整的配置文件參數(shù)參看c3p0的文檔
使用connection時(shí)很簡(jiǎn)單
Connection conn = ConnectionManager.getInstance().getConnection();
...
最后 conn.close() 即可,