简体   繁体   English

PreparedStatement与Connection的“关闭”之间的关系?

[英]Relationship between “close” for PreparedStatement and Connection?

Javadoc says for .close() of the PreparedStatement says that it .. Javadoc说PreparedStatement .close()说它...

Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. 立即释放此Statement对象的数据库和JDBC资源,而不是等待它自动关闭时发生。 It is generally good practice to release resources as soon as you are finished with them to avoid tying up database resources. 通常,最好在完成资源后立即释放资源,以避免占用数据库资源。

Calling the method close on a Statement object that is already closed has no effect. 在已关闭的Statement对象上调用close方法无效。

Note:When a Statement object is closed, its current ResultSet object, if one exists, is also closed. 注意:关闭Statement对象时,其当前ResultSet对象(如果存在)也将关闭。

Consider the following scenario 请考虑以下情形

    MyConnector databaseConnector = DBManager.instance().getConnector();

    Connection con = databaseConnector.getConnection(); // returns java.sql.Connection
    PreparedStatement pstmt = null;

    try {
        pstmt = con.prepareStatement("some query");
         ...
    } finally {  
        if (pstmt != null)
            pstmt.close();
    }

In this example, will pstmt.close() also close con ? 在这个例子中, pstmt.close()也会关闭con吗?

Closing a Statement doesn't close a Connection . 关闭Statement 不会关闭Connection However, closing a Connection will close a Statement . 但是,关闭Connection 关闭Statement

Think of it like so: 想象一下:

  • Connection -> creates and automatically closes -> Statement 连接 - >创建并自动关闭 - >语句
  • Statement -> creates and automatically closes -> ResultSet 语句 - >创建并自动关闭 - > ResultSet

So closing a Connection will automatically close any Statement s and any ResultSet s it contains. 因此,关闭Connection将自动关闭任何Statement 及其包含的任何ResultSet

However, it's still considered best practice to close all three manually ( ResultSet followed by Statement followed by Connection ) if possible. 但是,如果可能的话,仍然认为最好手动关闭所有三个( ResultSet后跟Statement后跟Connection )。

Note: When a Statement object is closed, its current ResultSet [but not Connection] object, if one exists, is also closed. 注意:当Statement对象关闭时,它的当前ResultSet [但不是Connection]对象(如果存在)也将关闭。

It wont close connection, it just closes resultset object. 它不会关闭连接,它只是关闭结果集对象。

If you are using Java 7 and try-with-resources you don't need to worry about closing the connection or any of the Statement or ResultSet . 如果您使用的是Java 7和try-with-resources ,则无需担心关闭连接或任何StatementResultSet

try (Connection conn = databaseConnector.getConnection();
     PreparedStatement pstmt = conn.prepareStatement("some query")) {
    ...
} catch (Exception e) {
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM