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?
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();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With