Reputation: 1497
Looking back over my code I find that I occasionaly have written:
ResultSet rs = conn.createStatement().executeQuery("select * from main");
//snip
rs.close();
and sometimes I've written
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("Select * from main");
//snip
rs.close();
st.close();
In the second code segment, it's more obvious that the Statement is closed, but is it also closed in the first one? conn.createStatement() returns a statement object, but when it's instantiated like that I don't see any easy way to close it after I'm done. Should I just rewrite the various bits of code to use method #2?
Upvotes: 3
Views: 113
Reputation: 18133
A good practice is to put the rs.close()
and st.close()
in your finally clause.
Statement st;
ResultSet rs;
try {
st = connection.createStatement(...);
rs = st.executeQuery();
}
catch (JdbcErrorsExceptionsAndFoo exception) {
// yadda yadda
}
finally {
if (rs!= null) {
rs.close();
}
if (st != null) {
st.close();
}
}
Upvotes: 2
Reputation: 60414
The Statement
will be automatically closed when it is garbage collected, but you need to explicitly close it if you want to free the resources as soon as you're done with them.
Note, however, that the reverse actually does work. That is, closing a Statement
also closes the ResultSet
associated with it.
Upvotes: 1
Reputation: 635
if statement contains a resultset, gc does not collect it. you can use the second method or use aspects or filters to auto close them.
Upvotes: 1