Search
 
SCRIPT & CODE EXAMPLE
 

SQL

java sql connection close

When you are done with using your Connection, you need to explicitly close it by calling its close() method in order to release any other database resources (cursors, handles, etc.) the connection may be holding on to.

Actually, the 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 this:

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

try {
    // Do stuff
    ...

} catch (SQLException ex) {
    // Exception handling stuff
    ...
} finally {
    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException e) { /* Ignored */}
    }
    if (ps != null) {
        try {
            ps.close();
        } catch (SQLException e) { /* Ignored */}
    }
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) { /* Ignored */}
    }
}
The finally block can be slightly improved into (to avoid the null check):

} finally {
    try { rs.close(); } catch (Exception e) { /* Ignored */ }
    try { ps.close(); } catch (Exception e) { /* Ignored */ }
    try { conn.close(); } catch (Exception e) { /* Ignored */ }
}
But, still, this is extremely verbose so you generally end up using an helper class to close the objects in null-safe helper methods and the finally block becomes something like this:

} finally {
    DbUtils.closeQuietly(rs);
    DbUtils.closeQuietly(ps);
    DbUtils.closeQuietly(conn);
}
And, actually, the Apache Commons DbUtils has a DbUtils class which is precisely doing that, so there isn't any need to write your own.
Comment

PREVIOUS NEXT
Code Example
Sql :: mysql show column type 
Sql :: mssql default connection string 
Sql :: mysql copy table rows from one database to another 
Sql :: SELECT ALL TABLE INFO 
Sql :: create directory in sql server 
Sql :: sql recursive query 
Sql :: insert json file to mssql 
Sql :: sql revert migration 
Sql :: dump db only triggers mysql 
Sql :: sql max value in column 
Sql :: generate random data in mysql 
Sql :: t sql cursor tr 
Sql :: oracle sql trigger select into 
Sql :: what is subquery in sql 
Sql :: mysql stored procedure insert if not exists 
Sql :: how to put 0 or 000 depending IDCustomer length in sql server 
Sql :: sql server epoch to datetime 
Sql :: postgresql sum 
Sql :: function plsql 
Sql :: get last inserted primary key 
Sql :: mysqldump cli command 
Sql :: postgresql install with ansible 
Sql :: creating database with - 
Sql :: SQL UNIQUE Constraint 
Sql :: insert set mysql 
Sql :: delete join sql server 
Sql :: How do I install microsoft SQL on my Mac? 
Sql :: decimal to integer sql 
Sql :: aliasing in sql 
Sql :: dynamic soql escape the single quote 
ADD CONTENT
Topic
Content
Source link
Name
6+6 =