【问题标题】:Is it mandatory to put inner try-with-resources or everything inside one of the try-with-resources will be autoclosed?是否必须将内部 try-with-resources 或其中一个 try-with-resources 中的所有内容都自动关闭?
【发布时间】:2017-02-04 13:48:53
【问题描述】:

是否必须将内部 try-with-resources 或其中一个 try-with-resources 中的所有内容都自动关闭?

    try (BasicDataSource ds = BasicDataSourceFactory.createDataSource(dsProperties)) {

        // still necessary for Connection to close if inside
        // try-with-resources?
        try (Connection conn = ds.getConnection()) {

            String sql = "SELECT * FROM users";
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {

                try (ResultSet rs = stmt.executeQuery()) {

                    while (rs.next()) {
                        System.out.println(rs.getString("email"));
                        System.out.println(rs.getString("password"));
                    }

                }
            }

        }

    } catch (SQLException e) {

        e.printStackTrace();
    } catch (Exception e) {

        e.printStackTrace();
    }

【问题讨论】:

  • 为什么你使用很多try-with-resources,只使用一个并使用; 放置多个语句。它会负责关闭所有。
  • 谢谢@jack jay,这正是我想知道的

标签: java datasource try-with-resources


【解决方案1】:

在 try-with-resources 块中,只有 try 语句中的资源会被 try-with-resources 构造自动关闭。块内的其他资源不相关,必须管理(*)

但是,您可以在try 语句中放入多个资源, 而不是使用多个 try-with-resources(每个资源一个),例如:

try (PreparedStatement stmt = conn.prepareStatement(sql);
     ResultSet rs = stmt.executeQuery()) {
    while (rs.next()) {
        System.out.println(rs.getString("email"));
        System.out.println(rs.getString("password"));
    }
}

(*)正如@alexander-farber 在评论中指出的那样,还有一些资源会被其他机制自动关闭,例如ResultSetStatement 时被关闭生成它被关闭。尽管您没有明确管理这些资源,但它们是由它们的实现来管理的。

【讨论】:

猜你喜欢
  • 2019-03-12
  • 2017-12-04
  • 2014-05-05
  • 2016-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-01
相关资源
最近更新 更多