Discuss / Java / try-with-resources 嵌套的问题

try-with-resources 嵌套的问题

Topic source

来日_方

#1 Created at ... [Delete] [Delete and Lock User]
try (Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD) {
    try (Statement stmt = conn.createStatement()) {
        try (ResultSet rs = stmt.executeQuery("SELECT id, grade, name, gender FROM students WHERE gender=1")) {
            while (rs.next()) {
                long id = rs.getLong(1); // 注意:索引从1开始
                long grade = rs.getLong(2);
                String name = rs.getString(3);
                int gender = rs.getInt(4);
            }
        }
    }
}

这里的 try-with-resources 能够不嵌套,写在一个 try-with-resources里吗?

try (
  Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD;
  Statement stmt = conn.createStatement();
  ResultSet rs = stmt.executeQuery("SELECT id, grade, name, gender FROM students WHERE gender=1");
) {
      while (rs.next()) {
      long id = rs.getLong(1); // 注意:索引从1开始
      long grade = rs.getLong(2);
      String name = rs.getString(3);
      int gender = rs.getInt(4);
   }
}

像这样写 java 会自动释放里面的资源吗?

一直写 try(){} 包裹起来的确有些繁琐

查了一下,是可以的,写多个,释放多个


  • 1

Reply