Java, Software Development

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

This post demonstrates how to use Java JDBC API with try-with-resources database resources in the following order – ResultSet, Statement, and Connection.

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

Closing Database resources In Pre-Java 7

Java is an ancient programming language but not a primitive technology. If you work on legacy applications, you often encounter exceptions handling the old way.

Using Java try-with-resources With JDBC API

When using Java try-with-resources with database resources, we declare and initialize them within parentheses next to the try keyword. See lines 16-18. We create the Connection, Statement, and ResultSet objects as though we pass these statements as arguments to a method.

Note that the order we declare and initialize these variables matters. The codes work because the try-with-resources statement closes the resources in the reverse order from which the codes opened them. Supposed we shuffle the order by which we declare and initialize these variables, Java will close these resources in reverse order.

Less Boilerplate Codes

We can see that the Java codes with try-with-resources are more compact. However, this feature brings about implicit implementation in our codes from Java itself.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like