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 连接
				
        
 
            
        基础教程推荐
- 从 python 访问 JVM 2022-01-01
 - 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
 - 不推荐使用 Api 注释的描述 2022-01-01
 - Java 实例变量在两个语句中声明和初始化 2022-01-01
 - Java Swing计时器未清除 2022-01-01
 - 多个组件的复杂布局 2022-01-01
 - 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
 - 验证是否调用了所有 getter 方法 2022-01-01
 - 大摇大摆的枚举 2022-01-01
 - 在 Java 中创建日期的正确方法是什么? 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				