Created
April 12, 2020 08:41
-
-
Save saswata-dutta/370266ba744246ea36041db1faeee055 to your computer and use it in GitHub Desktop.
auto close jdbc resources
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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