Reputation: 2290
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();
}
}
Upvotes: 2
Views: 772
Reputation: 22972
I believe that most of the time less code is more clean code.Secondly readability does matter if you are working with a team and your team member can not read your code properly than it's definitely your fault.
In first case its look quite simple and easily understandable for the programmer who have worked with Java7
and removes the boiler plate code of closing the resources.In the second case you first initialized with null
and have finally block with try-close-catch
session.It is always better to go with the clean code which is the first one and note one more thing,
In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.
Problem with try-with-resource
is you can not use the resources out of the scope of try it will be limited to try
block while that's not the case in your second part.
Upvotes: 2