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?
The
Statementwill 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
Statementalso closes theResultSetassociated with it.