我当前正在创建一个在 MySQL 数据库上执行更新的应用程序。
我这里有以下代码:
public int execute(String script, Object... values) throws Exception
{
Connection con = datasource.getConnection();
PreparedStatement statement = null;
int num = 0;
try{
try{
statement = getConnection().prepareStatement(script);
for (int i = 1; i <= values.length; i++)
{
statement.setObject(i, values[i - 1]);
}
num = statement.executeUpdate();
}finally{
if(statement != null) statement.close();
}
}finally{
if(con != null) con.close();
}
return num;
}
查看数据库的进程列表后,很明显,直到整个数据源关闭后,连接才会关闭。
为什么连接没有关闭?
最佳答案
我不完全确定您的代码的结构,但我怀疑问题是您正在调用 getConnection().prepareStatement(script)。
您正在获取一个连接并将其分配给 con,并在最后关闭它。但是,从 getConnection() 的 Connection 返回的语句导致该连接保持打开状态。
您应该调用 con.prepareStatement(script)
您没有捕获异常或处理错误。您应该使用 Java 7 的 try-with-resources:
例如
public int execute(String script, Object... values) throws Exception {
try (Connection con = datasource.getConnection();
PreparedStatement statment = con.prepareStatement(script)) {
for (int i = 1; i <= values.length; i++)
{
statement.setObject(i, values[i - 1]);
}
return statement.executeUpdate();
} catch (SQLException ex) {
// handleException
}
}
这将确保错误得到处理并正确关闭所有资源。
关于java - DBCP 数据库连接未关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32210146/