Should I initialize Statement and ResultSet in try-with-resources Statement or just initialize in try block and close Statement and ResultSet in finally block.
I need to understand the best way to implement this according to the best practices
try-with-resources Statement
try(Connection connection = DriverManager.getConnection("url");
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("query")){
} catch (SQLException e) {
e.printStackTrace();
}
or try-catch with finally
Statement st = null;
ResultSet rs = null;
try(Connection connection = DriverManager.getConnection("url"))
{
st = connection.createStatement();
rs = st.executeQuery("query");
} catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
rs.close();
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}