Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relationship between "close" for PreparedStatement and Connection?

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

Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. 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.

Note:When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

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?

like image 817
James Raitsev Avatar asked May 09 '12 21:05

James Raitsev


2 Answers

Closing a Statement doesn't close a Connection. However, closing a Connection will close a Statement.

Think of it like so:

  • Connection -> creates and automatically closes -> Statement
  • Statement -> creates and automatically closes -> ResultSet

So closing a Connection will automatically close any Statements and any ResultSets it contains.

However, it's still considered best practice to close all three manually (ResultSet followed by Statement followed by Connection) if possible.

like image 106
Tim Pote Avatar answered Oct 13 '22 01:10

Tim Pote


Note: When a Statement object is closed, its current ResultSet [but not Connection] object, if one exists, is also closed.

It wont close connection, it just closes resultset object.

like image 37
kosa Avatar answered Oct 13 '22 01:10

kosa