Retrieving Data Using JDBC

The following Java code fragment executes a SQL SELECT statement that returns author names from the authors table and then iterates through the results one row at a time, printing out each author’s name:

java.sql.Statement statement = connection.createStatement( );
java.sql.ResultSet result = 
   statement.executeQuery("SELECT au_fname, au_lname FROM authors" );
while( result.next( ) ) {
   String fname = result.getString( 1 );
   if( result.wasNull( ) ) fname = "NULL";
   String lname = result.getString( 2 );
   if( result.wasNull( ) ) lname = "NULL";
   System.out.println( lname + ", " + fname );
}
result.close( );
statement.close( );

Warning

Column ordinals are all one-based (first column is 1, second is 2, etc.) in JDBC, which is different from the zero-based ordinals used by ADO.NET.

Use the following steps to execute query statements in JDBC:

  1. Create a JDBC Statement object by invoking the createStatement method on a valid Connection object:

    java.sql.Statement statement = connection.createStatement( );
  2. The query is executed by invoking one of the execute methods on the Statement object. Result sets from query statements are processed by JDBC ResultSet objects, which are returned from the executeQuery method of JDBC Statement objects.

    java.sql.ResultSet result = 
       statement.executeQuery("SELECT au_fname, au_lname FROM authors" );
  3. After creating a ResultSet object, you can iterate through one row at a time by invoking the next method. The next method returns a Boolean value, true ...

Get SQL in a Nutshell, 2nd 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.