且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该如何在JDBC中使用try-with-resources?

更新时间:2023-09-18 10:44:10

我意识到这是很久以前的事了已回答但希望建议另一种方法,以避免嵌套的try-with-resources双重阻止。

I realize this was long ago answered but want to suggest an additional approach that avoids the nested try-with-resources double block.

public List<User> getUser(int userId) {
    try (Connection con = DriverManager.getConnection(myConnectionURL);
         PreparedStatement ps = createPreparedStatement(con, userId); 
         ResultSet rs = ps.executeQuery()) {

         // process the resultset here, all resources will be cleaned up

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

private PreparedStatement createPreparedStatement(Connection con, int userId) throws SQLException {
    String sql = "SELECT id, username FROM users WHERE id = ?";
    PreparedStatement ps = con.prepareStatement(sql);
    ps.setInt(1, userId);
    return ps;
}