67,513
社区成员
发帖
与我相关
我的任务
分享
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)
pstmt.close();
if (rs != null)
rs.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
log.error("close conn error ", e);
}
}
}
public class Test {
public static void main(String[] args) {
Connection conn = DBPool.getInstance().getConnection("erpt");
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
pstmt= conn.prepareStatement("select * from daily_aop limit 5;");
rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBPool.getInstance().close(pstmt, rs, conn);
}
}
}
synchronized (dataSources) {
dataSources.put(connName, dataSource);
}
怎么配置?