Relationship between "close" for PreparedStatement and Connection?

database, java, prepared-statement

Solution

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 `Statement`s and any `ResultSet`s it contains.

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

Problem

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`?

Original source