我正在使用 c3p0 - ComboPooledDataSource。我正在如下初始化一次。
private void init() {
cpds = new ComboPooledDataSource();
cpds.setDriverClass(driverName);
cpds.setJdbcUrl(url);
cpds.setUser(userName);
cpds.setPassword(pwd);
}
我正在从池中获取连接,如下所示
public synchronized Connection getLocalConnection(String ipAddr)
throws SQLException {
return cpds.getConnection();
}
但是我不确定在我完成查询后将连接返回到池中是否是正确的方法。我猜是
conn.close()
只是将连接返回到池中而不是真正关闭连接。 我是对的还是有其他办法?请帮忙。
最佳答案
这是初始化代码
private DataSource init() {
DataSource unpooled = DataSources.unpooledDataSource(DB_URL, DB_USERNAME, DB_PASSWORD);
Map<String, Object> overrideProps = new HashMap<String, Object>();
overrideProps.put("maxPoolSize", MAX_POOL_SIZE);
overrideProps.put("minPoolSize", MIN_POOL_SIZE);
return DataSources.pooledDataSource(unpooled, overrideProps);
}
然后您从 DataSource 获得连接。
public Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
要关闭连接,只需调用 close() 方法即可。
connection.close();
关于java - 如何在 c3p0 中返回连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5754461/