Skip to content

Instantly share code, notes, and snippets.

@saswata-dutta
Created April 12, 2020 08:41
Show Gist options
  • Save saswata-dutta/370266ba744246ea36041db1faeee055 to your computer and use it in GitHub Desktop.
Save saswata-dutta/370266ba744246ea36041db1faeee055 to your computer and use it in GitHub Desktop.
auto close jdbc resources
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment