Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this jdbc resource closed?

Tags:

java

jdbc

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?

like image 861
EricR Avatar asked Mar 14 '26 17:03

EricR


2 Answers

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();
    }
}
like image 119
Marvo Avatar answered Mar 17 '26 05:03

Marvo


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.

like image 41
Wayne Avatar answered Mar 17 '26 06:03

Wayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!