Java Reference
In-Depth Information
}
} catch (SQLException e) {
e.printStackTrace();
}
The resulting output from running this code should look similar to the following:
Successfully connected
13-1 Connecting to a Database DriverManager and
DataSource Implementations - More to Come
13-2 Querying a Database and Retrieving Results Subject
to Change
13-3
Handling SQL Exceptions Using SQLException
How It Works
Handling JDBC resources has always been a pain in the neck. There is a lot of boiler-
plate code that is required for closing resources when they are no longer needed. Since
the release of Java SE 7, this has not been the case. Java 7 introduced automatic re-
source management using try-with-resources . Through the use of this tech-
nique, the developer no longer needs to close each resource manually, which is a
change that can cut down on many lines of code.
In order to use this technique, you must instantiate all the resources for which you
want to have automatic handling enabled within a set of parentheses after a try
clause. In the solution to this recipe, the resources that are declared are Connection ,
Statement , and ResultSet .
try (Connection conn = createConn.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(qry);) {
Once those resources are out of scope, they are automatically closed. This means
there is no longer a requirement to code a finally block to ensure that resources are
closed. The automatic resource handling is not only available to database work, but to
any resource that complies with the new java.lang.Autocloseable API. Other
operations such as file I/O adhere to the new API as well. There is a single close()
method within java.lang.Autoclosable that manages the closing of the re-
Search WWH ::




Custom Search