Results
When an SQL query executes, the results form a pseudo-table that contains all rows that fit the query criteria. For instance, here’s a textual representation of the results of the query string “SELECT NAME, CUSTOMER_ID, PHONE FROM CUSTOMERS”:
NAME CUSTOMER_ID PHONE -------------------------------- ----------- ------------------- Jane Markham 1 617 555-1212 Louis Smith 2 617 555-1213 Woodrow Lang 3 508 555-7171 Dr. John Smith 4 (011) 42 323-1239
This kind of textual
representation is not very useful for Java programs. Instead, JDBC
uses the java.sql.ResultSet
interface to
encapsulate the query results as Java primitive types and objects.
You can think of a ResultSet
as an object that
represents an underlying table of query results, where you use method
calls to navigate between rows and retrieve particular column values.
A Java program might handle the previous query as follows:
Statement stmt = con.createStatement( ); ResultSet rs = stmt.executeQuery( "SELECT NAME, CUSTOMER_ID, PHONE FROM CUSTOMERS"); while(rs.next( )) { System.out.print("Customer #" + rs.getString("CUSTOMER_ID")); System.out.print(", " + rs.getString("NAME")); System.out.println(", is at " + rs.getString("PHONE"); } rs.close( ); stmt.close( );
Here’s the resulting output:
Customer #1, Jane Markham, is at 617 555-1212 Customer #2, Louis Smith, is at 617 555-1213 Customer #3, Woodrow Lang, is at 508 555-7171 Customer #4, Dr. John Smith, is at (011) 42 323-1239
The code
loops through each row of the ResultSet ...
Get Java Enterprise in a Nutshell, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.