PreparedStatement与Connection的"关闭"之间的关系?

Jam*_*sev 6 java database prepared-statement

的Javadoc说,对.close()PreparedStatement说,它..

立即释放此Statement对象的数据库和JDBC资源,而不是等待它自动关闭时发生.通常,最好在完成资源后立即释放资源,以避免占用数据库资源.

在已关闭的Statement对象上调用close方法无效.

注意:关闭Statement对象时,其当前ResultSet对象(如果存在)也将关闭.

请考虑以下情形

    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();
    }
Run Code Online (Sandbox Code Playgroud)

在这个例子中,pstmt.close()还会关闭con吗?

Tim*_*ote 12

关闭a Statement 关闭a Connection.然而,收盘Connection 关闭一个Statement.

想象一下:

  • 连接 - >创建并自动关闭 - >语句
  • 语句 - >创建并自动关闭 - > ResultSet

因此,关闭一个Connection会自动关闭任何Statements 及其ResultSet包含的任何内容.

但是,如果可能的话,仍然认为最好的做法是手动关闭所有三个(ResultSet后面Statement跟着Connection).