在 Java 中关闭数据库连接

2022-08-31 08:14:47

我有点困惑。我正在阅读Java数据库连接中的以下内容:

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.close()没有发生,到底发生了什么?conn

我有一个我正在维护的私有Web应用程序,它目前没有关闭任何一个表单,但是重要的一个真的是一个,一个,还是两者兼而有之?stmtconn

该网站不断间歇性地关闭,但服务器一直说这是一个数据库连接问题。我怀疑它没有被关闭,但我不知道关闭哪个(如果有的话)。


答案 1

使用完后,您需要通过调用其方法显式关闭它,以便释放连接可能保持的任何其他数据库资源(游标、句柄等)。Connectionclose()

实际上,Java 中的安全模式是在完成操作后在块中关闭 、 和 (按该顺序)。像这样:ResultSetStatementConnectionfinally

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

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

但是,这仍然非常详细,因此您通常最终会使用帮助器类来关闭 null 安全帮助程序方法中的对象,并且该块将变为如下所示:finally

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

而且,实际上,Apache Commons DbUtils有一个DbUtils类,它正是这样做的,所以没有必要编写自己的类。


答案 2

使用后关闭数据库/资源对象总是更好。最好关闭块中的连接、结果集和语句对象。finally

在Java 7之前,所有这些资源都需要使用块来关闭。如果您使用的是 Java 7,那么要关闭资源,可以执行以下操作。finally

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

    // Statements
}
catch(....){}

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


推荐