Java 7 自动资源管理 JDBC(try-with-resources 语句) [英] Java 7 Automatic Resource Management JDBC (try-with-resources statement)

查看:33
本文介绍了Java 7 自动资源管理 JDBC(try-with-resources 语句)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to integrate the common JDBC idiom of creating/receiving a connection, querying the database and possibly processing the results with Java 7's automatic resource management, the try-with-resources statement? (Tutorial)

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

Before Java 7, the usual pattern was something like this:

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();
}

使用 Java 7,您可以:

With Java 7 you can go for:

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

   ...
   con.commit();
}

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

This will close the Connection and the PreparedStatement, but what about the rollback? I cannot add a catch clause containing the rollback, because the connection is only available within the try block.

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

Do you still define the connection outside of the try block? What is the best practice here, especially if connection pooling is used?

推荐答案

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
   }
}

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

According to the oracle documentation, you can combine a try-with-resources block with a regular try block. IMO, the above example captures the correct logic, which is:

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

在 java 6 及更早版本中,我将使用一组三层嵌套的 try 块(外部 try-finally、中间 try-catch、内部 try-finally)来完成此操作.ARM 语法确实使这个更简洁.

In java 6 and earlier, I would do this with a triply nested set of try blocks (outer try-finally, middle try-catch, inner try-finally). ARM syntax does make this terser.

这篇关于Java 7 自动资源管理 JDBC(try-with-resources 语句)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆