简体   繁体   中英

Properly closing JDBC connection objects

As far as I understood, closing the connection objects in finally block is the best practice. However, if rs.close() / ps.close() throws an exception at the finally block, it won't execute the conn.close() . Therefore I used to close connections at two positions (as in sample provided), once directly after use, and secondly additionally in a finally-block using a check for null. But some consider block 1 as redundant code. Is it really redundant or is there proper way to address this issue without closing the connection in two places?

Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
    conn = dataSource.getConnection(); // geting the connection object
    ps = connection.prepareStatement(INSERT_QUERY);
    rs = ps.executeQuery();
    // some logic here ...
    // ---- block 1 ----
    ps.close()
    ps = null;
    rs.close();
    rs = null;
    conn.close();
    conn = null;
    // ---- end block 1 ----
} catch (SQLException e) {
    // exception handling ...
} finally {
    closeQuietly(conn, ps, rs);
}

private void closeQuietly(Connection connection, PreparedStatement ps, ResultSet rs) {
    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException e) {}
    }
    if (ps != null) {
        try {
            ps.close();
        } catch (SQLException e) {}
    }
    if (connection != null) {
        try {
            connection.close();
        } catch (SQLException e) {}
    }
}

is there proper way to address this issue without closing the connection in two places?

Yes:

try (Connection conn = dataSource.getConnection(); // geting the connection object
    Prepared Statement ps = connection.prepareStatement(INSERT_QUERY);
    ResultSet rs = ps.executeQuery();) {
    // ...
}

This is the 'try-with-resources' syntax. Everything declared inside the () after the try is guaranteed to be closed.

Yes, it would be called twice if everything goes fine with your code. That's the reason, people prefer to close any sort of connections (jdbc, stream etc) in the finally block. As you know, The finally block gets executed whether program executed correctly or not. So, I would recommend that you should not closing code after the use.


Jitendra

Block 1 is indeed redundant, as closeQuietly will always run due to the finally block.

closeQuietly does the right thing: As each resource is surrounded by its own try-catch block, the code to cleanup the connection will run even if the block closing the statement or resultset throw exceptions: Those exceptions will be caught and ignored by their try-catch blocks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM