How to properly clean up JDBC resources in Java?

后端 未结 9 1944
说谎
说谎 2020-12-16 03:17

What is considered best practices when cleaning up JDBC resources and why? I kept the example short, thus just the cleaning up of the ResultSet.

finally
{
          


        
9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 03:38

    This is my approach for JDK 6. If you have JDK 7+ you better use the approach I describe here https://stackoverflow.com/a/9200053/259237

    private void querySomething() {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet rs = null;
        try {
            // get connection
            // prepare statement
            // execute query
            // and so on
        } catch (SQLException e) {
            throw new MyException("Error while talking to database", e);
        } finally {
            close(connection, statement, rs);
        }
    }
    
    // useful because you probably have more than one method interacting with database
    public static void close (Connection connection, Statement statement, ResultSet rs) {
        if (rs != null) {
            try { rs.close(); } catch (Exception e) { _logger.warning(e.toString()); }
        }
        if (statement != null) {
            try { statement.close(); } catch (Exception e) { _logger.warning(e.toString()); }
        }
        if (connection != null) {
            try { connection.close(); } catch (Exception e) { _logger.warning(e.toString()); }
        }
    }
    
    • It's short.
    • It defines a close method that can be statically imported.
    • It avoids empty catch blocks.
    • It handles any SQLException that may occur (even in getConnection or close methods).
    • It's null-safe.

提交回复
热议问题