代码之家  ›  专栏  ›  技术社区  ›  onaclov2000

在Java中关闭数据库连接

  •  99
  • onaclov2000  · 技术社区  · 15 年前

    我有点糊涂了。我正在读下面的文章 Java Database Connectivity :

    Connection conn = DriverManager.getConnection(
         "jdbc:somejdbcvendor:other data needed by some jdbc vendor",
         "myLogin",
         "myPassword" );
    
    Statement stmt = conn.createStatement();
    try {
        stmt.executeUpdate( "INSERT INTO MyTable( name ) VALUES ( 'my name' ) " );
    } finally {
        // It's important to close the statement when you are done with it
        stmt.close();
    }
    

    conn 联系? 如果conn.close()没有发生,会发生什么?

    stmt 一是 康涅狄格州 一个,还是两个?

    6 回复  |  直到 4 年前
        1
  •  210
  •   Peter Mortensen icecrime    4 年前

    Connection ,您需要通过调用其 close()

    ResultSet Statement 联系 (按该顺序)以 finally

    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 */}
        }
    }
    

    这个 块可以稍微改进为(以避免空检查):

    } finally {
        try { rs.close(); } catch (Exception e) { /* Ignored */ }
        try { ps.close(); } catch (Exception e) { /* Ignored */ }
        try { conn.close(); } catch (Exception e) { /* Ignored */ }
    }
    

    但是,这仍然是非常冗长的,因此您通常会使用一个helper类来关闭空安全helper方法和 最后 块变成如下所示:

    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(ps);
        DbUtils.closeQuietly(conn);
    }
    

    Apache Commons DbUtils 有一个 DbUtils

        2
  •  65
  •   Peter Mortensen icecrime    4 年前

    使用后最好关闭数据库/资源对象。 finally

    在Java7之前,所有这些资源都需要使用 最后 块如果您使用的是Java7,那么为了关闭资源,您可以执行以下操作。

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

    con stmt rs 对象成为try块的一部分,Java在使用后自动关闭这些资源。

        3
  •  14
  •   Peter Mortensen icecrime    4 年前

    只要关门就够了 Statement Connection . 没有必要显式地关闭 ResultSet 对象

    Java文档介绍了 java.sql.ResultSet

    当一个ResultSet对象被关闭、重新执行或用于从多个结果序列中检索下一个结果时,生成它的语句对象会自动关闭该对象。


    BalusC for comments : “我不会相信的。一些JDBC驱动程序在这方面失败。”

        4
  •  11
  •   Brian Agnew    15 年前

    对您需要关闭结果集、语句和连接。如果连接来自池,关闭它实际上会将其发送回池以供重用。

    您通常必须在一个特定的时间内完成此操作 finally{} 块,这样,如果抛出异常,您仍然有机会关闭它。

    JdbcTemplate . Apache DbUtils 在关闭resultset/statement/connection(无论是否为null)后(以及在关闭时捕获异常)有一些方法,这也可能会有所帮助。

        5
  •  8
  •   Peter Mortensen icecrime    4 年前

    事实上,最好使用 try-with-resources block

    您应该对实现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.");
    }
    

    对getDatabaseConnection的调用刚刚完成。将其替换为获取JDBCSQL连接或池连接的调用。

        6
  •  7
  •   Peter Mortensen icecrime    4 年前

    是的,你需要关门 Connection