O'Reilly logo

SQL in a Nutshell by Kevin Kline

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required