Java Reference
In-Depth Information
String qry = "select recipe_num, name, 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_NUM");
String name = rs.getString("NAME");
String desc = rs.getString("DESCRIPTION");
System.out.println(recipe + "\t" + name + "\t"
+ desc);
}
} catch (SQLException e) {
e.printStackTrace();
}
If you execute this code using the database script that is included with Chapter 13 ,
you will receive the following results:
13-1 Connecting to a Database DriverManager and
DataSource Implementations
13-2 Querying a Database and Retrieving Results
Obtaining and Using Data from a DBMS
13-3
Handling SQL Exceptions Using SQLException
How It Works
One of the most commonly performed operations against a database is a query. Per-
forming database queries using JDBC is quite easy, although there is a bit of boilerplate
code that needs to be used each time a query is executed. First, you need to obtain a
Connection object for the database and schema that you want to run the query
against. You can do this by using one of the solutions found in Recipe 13-1. Next, you
need to form a query and store it in string format. The Connection object is then
used to create a Statement . Your query string will be passed to the Statement ob-
ject's executeQuery() method in order to actually query the database. Here, you
can see what this looks like without the use of try-with-resources for resource
management.
Search WWH ::




Custom Search