0

Java – Closing JDBC Database Resources with try-with-resources

This post demonstrates how to use try-with-resources to close JDBC database resources in this order – ResultSet, Statement, and Connection.

The Try-with-resources is a new exception handling mechanism that makes it easier to correctly close resources that are used within a try-catch block. It has been available since Java 7.

Pre-Java 7 Example

If you work on legacy applications, you often encounter exception handling this way:

How to connect to MySQL using JDBC

Using Try-with-resources

The codes work because try-with-resources statement closes the resources in the reverse order from which they were opened.

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert