Where to close a JDBC Connection while I want to return the ResultSet(我想返回 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()
                        这篇关于我想返回 ResultSet 时在哪里关闭 JDBC 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我想返回 ResultSet 时在哪里关闭 JDBC 连接
				
        
 
            
        - GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
 - 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
 - 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
 - 转换 ldap 日期 2022-01-01
 - 如何指定 CORS 的响应标头? 2022-01-01
 - Eclipse 的最佳 XML 编辑器 2022-01-01
 - 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
 - java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
 - 获取数字的最后一位 2022-01-01
 - 未找到/usr/local/lib 中的库 2022-01-01
 
						
						
						
						
						
				
				
				
				