Java Reference
In-Depth Information
In Java 8, the new Date-Time API ( Chapter 4 ) is the preferred API for working with
dates and times. Therefore, when working with date values and databases, the JDBC
API must convert between SQL dates and new Date-Time LocalDate objects. The
solution to this recipe demonstrates that to obtain an instance of java.sql.Date
from a LocalDate object, you simply invoke the static
java.sql.Date.valueOf() method, passing the pertinent LocalDate object.
13-16.
Handling
Resources
Automatic-
ally
Problem
Rather than manually opening and closing resources with each database call, you
would prefer to have the application handle such boilerplate code for you.
Solution
Use the try-with-resources syntax to automatically close the resources that you
open. The following block of code uses this tactic to automatically close the Connec-
tion , Statement , and ResultSet resources when it is finished using them:
String qry = "select recipe_number, recipename,
description from recipes";
try (Connection conn = createConn.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(qry);) {
while (rs.next()) {
String recipe = rs.getString("RECIPE_NUMBER");
String name = rs.getString("RECIPE_NAME");
String desc = rs.getString("DESCRIPTION");
System.out.println(recipe + "\t" + name + "\t"
+ desc);
Search WWH ::




Custom Search