【问题标题】:Efficient way to close multiple statements and resultsets?关闭多个语句和结果集的有效方法?
【发布时间】:2021-03-25 13:17:14
【问题描述】:

我尝试在一个 finally 块中将它们全部关闭,但它导致了 ORA-01000ORA-00604 错误。所以现在,我所做的是,每个语句和结果集都有自己的 try-catch-finally 块。它工作得非常好,但我仍然想知道是否有更有效的方法来关闭所有语句和结果集

try{
    Connection conn = HikariCp.getConnection();

    try{
        String sql1 = "SELECT * FROM TABLE1";
        PreparedStatement pst1 = conn.prepareStatement(sql1);
        ResultSet rs1 = pst1.executeQuery();

    }catch(SQLException e){
        JOptionPane.showMessageDialog(this,e.getMessage());
    }finally{
        try { if (rs1 != null) rs1.close(); } catch (Exception e) {};
        try { if (pst1 != null) pst1.close(); } catch (Exception e) {};
    }

    try{
        String sql2 = "SELECT * FROM TABLE2";
        PreparedStatement pst2 = conn.prepareStatement(sql2);
        ResultSet rs2 = pst2.executeQuery();

    }catch(SQLException e){
        JOptionPane.showMessageDialog(this,e.getMessage());
        
    }finally{
        try { if (rs2 != null) rs2.close(); } catch (Exception e) {};
        try { if (pst2 != null) pst2.close(); } catch (Exception e) {};
    }

    try{
        String sql2 = "SELECT * FROM TABLE3";
        PreparedStatement pst3 = conn.prepareStatement(sql3);
        ResultSet rs3 = pst3.executeQuery();

    }catch(SQLException e){
        JOptionPane.showMessageDialog(this,e.getMessage());
    }finally{
        try { if (rs3 != null) rs3.close(); } catch (Exception e) {};
        try { if (pst3 != null) pst3.close(); } catch (Exception e) {};
    }

}catch(Exception e){
    JOptionPane.showMessageDialog(this,e.getMessage());
}finally{
    try { if (conn != null) conn.close(); } catch (Exception e) {};
}

【问题讨论】:

标签: java sql oracle jdbc


【解决方案1】:

luk2302 所说的 - 使用 try-with-resources。这会在执行该块后自动关闭连接。

您最初在一个 finally 块中关闭所有连接的想法并不理想,因为您将未使用的连接保持打开状态。 根据您的数据库,您只能打开 X 个连接,因此这可能是错误的原因。

【讨论】:

    【解决方案2】:

    如果您可以使用 Spring JDBC 模板,那么您将不必关闭任何连接。 春天会照顾你的。

    private void create(Datasource dataSource) throws SQLException {
    
            JdbcTemplate template = new JdbcTemplate(dataSource);
            template.execute("your query");
        }
    

    【讨论】:

      猜你喜欢
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      相关资源
      最近更新 更多