Closing Database Connections in Java

前端 未结 6 1267
小鲜肉
小鲜肉 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:12

    It is always better to close the database/resource objects after usage. Better to close connection, resultset and statement objects in the finally block.

    Until Java7, all these resources needs to be closed using a finally block. If you are using Java 7, then for closing the resources you can do as follows.

    try(Connection con = getConnection(url, username, password, "org.postgresql.Driver");
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
    ) {
    
    //statements
    }catch(....){}
    

    Now, con, stmt and rs objects become part of try block and java automatically closes these resources after use.

    Hope I was helpful.

    0 讨论(0)
  • 2020-11-22 10:13

    Yes, you need to close the Connection. Otherwise, the database client will typically keep the socket connection and other resources open.

    0 讨论(0)
  • 2020-11-22 10:14

    It is enough to close just Statement and Connection. There is no need to explicitly close the ResultSet object.

    Java documentation says about java.sql.ResultSet:

    A ResultSet object is automatically closed by the Statement object that generated it when that Statement object is closed, re-executed, or is used to retrieve the next result from a sequence of multiple results.


    Thanks BalusC for comments: "I wouldn't rely on that. Some JDBC drivers fail on that."

    0 讨论(0)
  • 2020-11-22 10:14

    Yes. You need to close the resultset, the statement and the connection. If the connection has come from a pool, closing it actually sends it back to the pool for reuse.

    You typically have to do this in a finally{} block, such that if an exception is thrown, you still get the chance to close this.

    Many frameworks will look after this resource allocation/deallocation issue for you. e.g. Spring's JdbcTemplate. Apache DbUtils has methods to look after closing the resultset/statement/connection whether null or not (and catching exceptions upon closing), which may also help.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 10:34

    Actually, it is best if you use a try-with-resources block and Java will close all of the connections for you when you exit the try block.

    You should do this with any object that implements AutoClosable.

    try (Connection connection = getDatabaseConnection(); Statement statement = connection.createStatement()) {
        String sqlToExecute = "SELECT * FROM persons";
        try (ResultSet resultSet = statement.execute(sqlToExecute)) {
            if (resultSet.next()) {
                System.out.println(resultSet.getString("name");
            }
        }
    } catch (SQLException e) {
        System.out.println("Failed to select persons.");
    }
    

    The call to getDatabaseConnection is just made up. Replace it with a call that gets you a JDBC SQL connection or a connection from a pool.

    0 讨论(0)
提交回复
热议问题