我想返回 ResultSet 时在哪里关闭 JDBC 连接
当我关闭 Connection
时,似乎 ResultSet
会自动关闭.但是我想返回 ResultSet
并在另一个方法中使用它,然后我不知道在哪里关闭 Connection
和 PreparedStatement
.
It seems that the ResultSet
will be automatically closed when I close the Connection
.
But I want to return the ResultSet
and use it in another method, then I don't know where to close Connection
and PreparedStatement
.
public ResultSet executeQuery(String sql, String[] getValue)
{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
conn = getConn();
pstmt = conn.prepareStatement(sql);
if (getValue != null)
{
for (int i = 0; i < getValue.length; i++)
{
pstmt.setString(i + 1, getValue[i]);
}
}
rs = pstmt.executeQuery();
} catch (Exception e)
{
e.printStackTrace();
closeAll(conn, pstmt, rs);
}
return rs;
}
我已将 closeAll(conn, pstmt, null);
移动到 catch 块中,因为我发现如果我将其放入 finally 块中,我将丢失我的 rs
就在它返回之前.现在当我想关闭 rs
时,我无法关闭 conn
和 pstmt
.有什么解决办法吗?
I've moved closeAll(conn, pstmt, null);
into catch block because I found that if I put it in finally block I'll lost my rs
immediately just before it returns.
Now when I want to close the rs
, I can't close the conn
and pstmt
. Is there any solution?
推荐答案
断开后使用CachedRowSet
保存信息
Connection con = ...
ResultSet rs = ...
CachedRowSet rowset = new CachedRowSetImpl();
rowset.populate(rs);
con.close()
相关文章