在try-with-resources中获得连接时,try-catch块中的准备好的语句是否自动关闭

时间:2019-08-15 15:29:01

标签: java sql connection try-with-resources autocloseable

我使用 try-with-resources 建立连接并在其中执行一些sql操作。 作为try-with-resources的功能,我的连接自动关闭。准备好的语句和结果集会自动关闭还是我会显式关闭它们?

以下哪一项更合适?

// Snippet 1 - Closing prepared statements and result set explicitly
try(Connection conn = ConnectionManager.getConnection()) {
    PreparedStatement statement = conn.prepareStatement("SELECT 1");
    final ResultSet resultSet = statement.executeQuery();
    // Additional logic on using those
    statement.close();
    resultSet.close();
} catch (SQLException e) {
    log.error("SQL Exception", e);
}
// Snippet 2 - Will AutoClosable do the magic?
try(Connection conn = ConnectionManager.getConnection()) {
    PreparedStatement statement = conn.prepareStatement("SELECT 1");
    final ResultSet resultSet = statement.executeQuery();
} catch (SQLException e) {
    log.error("SQL Exception", e);
}

0 个答案:

没有答案