Java 关闭多个语句和结果集的有效方法?

Java 关闭多个语句和结果集的有效方法?,java,sql,oracle,jdbc,Java,Sql,Oracle,Jdbc,我试图在一个finally块中全部关闭它们,但它导致了一个ORA-01000和ORA-00604错误。现在,我做的是,每个语句和结果集都有自己的try-catch-finally块。它工作得非常好,但我仍然想知道是否有更有效的方法来关闭所有语句和结果集 try{ Connection conn = HikariCp.getConnection(); try{ String sql1 = "SELECT * FROM TABLE1";

我试图在一个finally块中全部关闭它们,但它导致了一个
ORA-01000
ORA-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) {};
}

luk2302所说的-使用
尝试使用资源
。这将在执行该块后自动关闭连接

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

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

private void create(Datasource dataSource) throws SQLException {

        JdbcTemplate template = new JdbcTemplate(dataSource);
        template.execute("your query");
    }
这应该会缩短很多。