日期:2014-05-18  浏览次数:20781 次

写了个通用连接池,c3p0,用来连接多个数据库,大家看看有没有问题
要实现的功能,就是读取jdbc.properties,获取数据库连接。
只要在jdbc.properties配置了url,username,password三项就可以调用DBPool实现数据库连接,是连接池的。


import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DBPool {

private static Logger log = Logger.getLogger(DBPool.class);
private static DBPool dbPool = new DBPool();

private static Map<String, ComboPooledDataSource> dataSources = new ConcurrentHashMap<String, ComboPooledDataSource>();

private DBPool() {
}

public final static DBPool getInstance() {
return dbPool;
}

public final Connection getConnection(String connName) {
try {
Connection conn = getDataSource(connName).getConnection();
return conn;
} catch (SQLException e) {
log.error("can't get the connection :" + e);
throw new RuntimeException("unable to connect to the database ", e);
}
}

private ComboPooledDataSource getDataSource(String connName) {

ComboPooledDataSource dataSource = dataSources.get(connName);

if (dataSource != null) {
return dataSource;
}

try {
InputStream is = DBPool.class.getResourceAsStream("/jdbc.properties");
Properties p = new Properties();
p.load(is);
String dbUrl = p.getProperty(connName + ".url");
String dbUser = p.getProperty(connName + ".username");
String dbPwd = p.getProperty(connName + ".password");
String driver = p.getProperty("driver");
dataSource = new ComboPooledDataSource();
dataSource.setUser(dbUser);
dataSource.setPassword(dbPwd);
dataSource.setJdbcUrl(dbUrl);
dataSource.setDriverClass(driver);
dataSource.setInitialPoolSize(2);
dataSource.setMinPoolSize(1);
dataSource.setMaxPoolSize(10);
dataSource.setMaxStatements(50);
dataSource.setMaxIdleTime(60);
dataSource.setAcquireIncrement(5);
is.close();
} catch (PropertyVetoException e) {
log.error("jdbc.properties error ", e);
} catch (Exception e) {
log.error("datasource generate error ", e);
}

dataSources.put(connName, dataSource);

return dataSource;
}

public final void close(Statement pstmt, ResultSet rs, Connection conn) {
try {
if (pstmt != null)