Closing Database Connections in Java

前端 未结 6 1329
小鲜肉
小鲜肉 2020-11-22 09:34

I am getting a little confused, I was reading the below from http://en.wikipedia.org/wiki/Java_Database_Connectivity

Connection conn = DriverManager.getConn         


        
6条回答
  •  滥情空心
    2020-11-22 10:25

    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 that:

    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 that:

    } 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 is no need to write your own.

提交回复
热议问题