编程语言
首页 > 编程语言> > java-新的jre7 try块资源

java-新的jre7 try块资源

作者:互联网

如果我做类似的事情

    try (
        Connection conn = Database.getConnection();
        PreparedStatement ps = conn.prepareStatement("SELECT * FROM table WHERE something = ? LIMIT 1");
    ) {
        ps.setString(1, "hello world");
        ResultSet results = ps.executeQuery();
        if(results.next()) {
            // blah
        }
    } catch(SQLException e) {
        e.printStackTrace();
    }

在关闭PreparedStatement时是否仍将关闭ResultSet,还是还必须显式关闭ResultSet?

解决方法:

按照javax.sql.Statement.close()方法的JavaDoc:

Note:When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

因此,回答您的问题-是的,在您的情况下,ResultSet将自动关闭,因为在try-with-resources块中关闭了相关的Statement.

但是,请注意,显式关闭ResultSets是一个好的做法,建议遵循此做法,因此,按照好的做法修改的代码如下所示:

try (
    Connection conn = Database.getConnection();
    PreparedStatement ps = prepareStatement(conn, "SELECT * FROM table WHERE something = ? LIMIT 1", param);
    ResultSet results = ps.executeQuery();
) {        
    if(results.next()) {
        // blah
    }
} catch(SQLException e) {
    e.printStackTrace();
}

private static PreparedStatement prepareStatement(Connection connection, String sql, String param) throws SQLException {
    final PreparedStatement ps = conn.prepareStatement(sql);
    ps.setString(1, param);
    return ps;
}

标签:java-7,try-catch,java
来源: https://codeday.me/bug/20191101/1981327.html