【发布时间】:2021-03-25 13:17:14
【问题描述】:
我尝试在一个 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) {};
}
【问题讨论】:
-
try-with-resources应该会缩短很多。