Java 7自动资源管理JDBC(try-with-resources语句)

TPe*_*ete 37 java jdbc java-7 try-with-resources

如何集成创建/接收连接,查询数据库以及可能使用Java 7的自动资源管理(try-with-resources语句)处理结果的常用JDBC习惯用法?(教程)

在Java 7之前,通常的模式是这样的:

Connection con = null;
PreparedStatement prep = null;

try{
    con = getConnection();
    prep = prep.prepareStatement("Update ...");
    ...
    con.commit();
}
catch (SQLException e){
    con.rollback(); 
    throw e;
}
finally{
    if (prep != null)
        prep.close();
    if (con != null)
        con.close();
}
Run Code Online (Sandbox Code Playgroud)

使用Java 7,您可以选择:

try(Connection con = getConnection(); PreparedStatement prep = con.prepareConnection("Update ..."){

   ...
   con.commit();
}
Run Code Online (Sandbox Code Playgroud)

这将关闭ConnectionPreparedStatement,但滚动呢?我无法添加包含回滚的catch子句,因为该连接仅在try块中可用.

你还在try块之外定义连接吗?这里的最佳做法是什么,尤其是在使用连接池的情况下?

Sea*_*lly 39

try(Connection con = getConnection()) {
   try (PreparedStatement prep = con.prepareConnection("Update ...")) {
       //prep.doSomething();
       //...
       //etc
       con.commit();
   } catch (SQLException e) {
       //any other actions necessary on failure
       con.rollback();
       //consider a re-throw, throwing a wrapping exception, etc
   }
}
Run Code Online (Sandbox Code Playgroud)

根据oracle文档,您可以将try-with-resources块与常规try块结合使用.IMO,上面的例子捕获了正确的逻辑,即:

  • 如果没有出错,请尝试关闭PreparedStatement
  • 如果内部块出现问题,(无论是什么)回滚当前事务
  • 无论如何都尝试关闭连接
  • 如果关闭连接出现问题,则无法回滚事务(因为这是连接上的方法,现在处于不确定状态),所以不要尝试

在java 6及更早版本中,我将使用三重嵌套的try块(外部try-finally,中间try-catch,内部try-finally)来完成此操作.ARM语法确实做到了这一点.