# Explicitly closing Statements, ResultSets, and Connections

You should explicitly close `Statements`, `ResultSets`, and `Connections` when you no longer need them, unless you declare them in a `try`-with-resources statement (available in JDK 7 and after).

Connections to Derby are resources external to an application, and the garbage collector will not close them automatically.

To close a `Statement`, `ResultSet`, or `Connection` object that is not declared in a `try`-with-resources statement, use its `close` method. If auto-commit is disabled, you must explicitly commit or roll back active transactions before you close the connection.

Statements, result sets, and connections extend `AutoCloseable` in JDK 7 and after. If you declare a connection in a `try`-with-resources statement and there is an error that the code does not catch, the JRE will attempt to close the connection automatically.

Note that a transaction-severity or higher exception causes Derby to abort an in-flight transaction. But a statement-severity exception does NOT roll back the transaction. Also note that Derby throws an exception if an attempt is made to close a connection with an in-flight transaction. Suppose now that a `Connection` is declared in a `try`-with-resources statement, a transaction is in-flight, and an unhandled statement-severity error occurs inside the `try`-with-resources block. In this situation, Derby will raise a follow-on exception as the JRE exits the try-with-resources block. (For details on error severity levels, see the documentation of the `derby.stream.error.logSeverityLevel` property in the Derby Reference Manual.)

It is therefore always best to catch errors inside the `try`-with-resources block and to either roll back or commit, as appropriate, to ensure that there is no pending transaction when leaving the `try`-with-resources block. This action also improves application portability, since DBMSs differ in their semantics when trying to close a connection with a pending transaction.

Parent topic: Transactions
Related concepts
Transactions when auto-commit is disabled
Using auto-commit
Statement versus transaction runtime rollback
Using savepoints
Related tasks
Turning off auto-commit