连接关闭时 ResultSet 未关闭? [英] ResultSet not closed when connection closed?

查看:67
本文介绍了连接关闭时 ResultSet 未关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在对我们的一个宠物项目进行代码审查(主要使用 FindBugs 之类的工具),并且 FindBugs 将以下代码标记为错误(伪代码):

I've been doing code review (mostly using tools like FindBugs) of one of our pet projects and FindBugs marked following code as erroneous (pseudocode):

Connection conn = dataSource.getConnection();

try{
    PreparedStatement stmt = conn.prepareStatement();
    //initialize the statement
    stmt.execute();
    ResultSet rs =  stmt.getResultSet();
    //get data
}finally{
    conn.close();
}

错误是此代码可能不会释放资源.我发现 ResultSet 和 Statement 没有关闭,所以我在 finally 中关闭了它们:

The error was that this code might not release resources. I figured out that the ResultSet and Statement were not closed, so I closed them in finally:

finally{
    try{
        rs.close()
    }catch(SqlException se){
        //log it
    }
    try{
        stmt.close();
    }catch(SqlException se){
        //log it
    }
    conn.close();
}

但是我在很多项目(来自不少公司)中遇到了上述模式,并且没有人关闭 ResultSets 或 Statements.

But I encountered the above pattern in many projects (from quite a few companies), and no one was closing ResultSets or Statements.

当连接关闭时,您是否遇到过结果集和语句未关闭的问题?

Did you have troubles with ResultSets and Statements not being closed when the Connection is closed?

我只发现了这个,它指的是 Oracle 在关闭连接时关闭结果集(我们使用 Oracle 数据库,因此我更正).java.sql.api 在 Connection.close() javadoc 中什么也没说.

I found only this and it refers to Oracle having problems with closing ResultSets when closing Connections (we use Oracle db, hence my corrections). java.sql.api says nothing in Connection.close() javadoc.

推荐答案

仅关闭连接而不关闭结果集的一个问题是,如果您的连接管理代码使用连接池,connection.close() 只会将连接放回池中.此外,某些数据库在服务器上有一个游标资源,除非明确关闭,否则不会正确释放.

One problem with ONLY closing the connection and not the result set, is that if your connection management code is using connection pooling, the connection.close() would just put the connection back in the pool. Additionally, some database have a cursor resource on the server that will not be freed properly unless it is explicitly closed.

这篇关于连接关闭时 ResultSet 未关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆