Java 17 Recipes


-4. Querying a Database and Retrieving Results


Download 3.2 Mb.
Pdf ko'rish
bet223/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   219   220   221   222   223   224   225   226   ...   245
Bog'liq
Java 17 Recipes

12-4. Querying a Database and Retrieving Results
 Problem
A process in your application needs to query a database table for data.
Chapter 12 Working With Databases


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

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   219   220   221   222   223   224   225   226   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling