AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.



jdbc-basics: Why should we close the database connection?

What will be happen if we don´t close the connection?

jdbc x 32
basics x 171
Posted On : 2014-01-06 16:09:49.0
profile Garima Gupta - anyforum.in Garima Gupta
596129560202
up-rate
3
down-rate

Answers


You should close the Connection. Otherwise, the database client will typically keep the socket connection and other resources open. If you are not closing the connection, It´d not release the resources and it´d create new connection remember there is a limited number of connection only. So it may result next user not to get the database connection. Actually, the proper and safe pattern in Java is to close your ResultSet, Statement, and Connection (in that order) in a finally block when you are done with them, something like that:

Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
// Do stuff
...

} catch (SQLException ex) {
// Exception handling stuff
...
}

finally {
try { rs.close(); } catch (Exception e) { /* ignored */ }
try { ps.close(); } catch (Exception e) { /* ignored */ }
try { conn.close(); } catch (Exception e) { /* ignored */ }
}

To improve the finally block more you should use the helper class to close the objects in null-safe helper methods and the finally block becomes something like that:

finally {
DbUtil.closeQuietly(rs);
DbUtil.closeQuietly(ps);
DbUtil.closeQuietly(conn);
}

Posted On : 2014-01-06 18:01:43
Satisfied : 1 Yes  0 No
profile Saksham Kumar - anyforum.in Saksham Kumar
73433939909
Reply This Thread
up-rate
5
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in