我有一个奇怪的问题。我有一个实用程序类,用于保存连接并具有准备语句的功能。然后运行这些语句,关闭它们,一切正常。
但是,当我尝试使用ComboPooledDataSource添加连接池时,我的线程关闭。我对其进行了调试,可以看到一些查询已成功执行,但是随后突然所有内容都关闭了,只有c3p0线程保持运行状态。没有抛出异常。
我尝试将池设置为单个连接,以尽可能接近地模拟工作代码,但这也失败了。如果将连接成员设置为来自池的连接,则一切正常,但是,如果尝试直接从池中使用,则会得到上面概述的行为。
这里有一些示例代码:
class DBUtilityClass
{
private java.sql.Connection connection;
private ComboPooledDataSource connectionPool;
public void DBUtilityClass()
{
connect();
}
private void connect()
{
connectionPool = new ComboPooledDataSource();
connectionPool.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver
connectionPool.setJdbcUrl(urlString.toString());
connectionPool.setUser(user);
connectionPool.setPassword(password);
connectionPool.setAutoCommitOnClose(true);
connectionPool.setInitialPoolSize(1);
connectionPool.setMinPoolSize(1);
connectionPool.setAcquireIncrement(1);
connectionPool.setMaxPoolSize(1);
}
//Version 1 - this works if I set the connection in the constructor
//or if I connect the connection manually without using the pool
public Connection getConnection()
{
connection.setAutoCommit(true);
return connection;
}
//Version 2 - This fails
public Connection getConnection()
{
Connection temp = connectionPool.getConnection();
temp.setAutoCommit(true);
return temp;
}
public PreparedStatement getPreparedStatement(String sql)
{
Connection temp = getConnection();
return temp.prepareStatement(sql);
}
}
您班上的函数public PreparedStatement getPreparedStatement(String sql)
是Connection
泄漏。每次调用它时,都会从池中获取一个Connection
,但是该引用将被删除,因此永远不会对其进行close()
处理并返回到池中。
((很抱歉,我们在上面的评论中,我花了这么长时间才看到它!)
[当有一个共享的Connection
时,没问题,一个Connection保持签出状态。但是,当您应该像使用池一样,及时检出连接并且不缓存它们时,必须确保完成后将它们close()
。
确保对getConnection()
的每次调用都与对close()
的调用匹配。最简单的方法是
try( Connection conn = myDBUtilityInstance.getConnection ) {
try( PreparedStatement ps = conn.prepareStatement( sql ) ) {
// do work here
}
}