436
Solution
Obtain
a JDBC connection, and then use the java.sql.Connection object to create a
Statement object. A java.sql.Statement object contains the executeQuery() method,
which parses a string of text and uses it to query a database. Once you’ve
executed the
query, you can retrieve the results in a ResultSet object. The following example queries
a database table named RECIPES and prints the results.
public class QueryDatabase {
private static CreateConnection createConn;
public static void main(String[] args) {
createConn = new CreateConnection();
queryDatabase();
}
public static void queryDatabase() {
String qry = "select recipe_num, recipe_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("RECIPE_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 included with Chapter
12
, you
receive the following results.
Chapter 12 Working With Databases
437
12-1 Installing MySQL Downloading and installation of a MySQL Database
12-2 Connecting to a Database DriverManager and
DataSource Implementations
12-3 Handling SQL Exceptions Using SQLException
12-4 Querying a Database and Retrieving Results Obtaining
and using data
from a DBMS
Do'stlaringiz bilan baham: