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.Statementstatement
=connection
.createStatement( ); java.sql.ResultSetresult
=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:
Create a JDBC
Statement
object by invoking thecreateStatement
method on a validConnection
object:java.sql.Statement
statement
=connection
.createStatement( );The query is executed by invoking one of the
execute
methods on theStatement
object. Result sets from query statements are processed by JDBCResultSet
objects, which are returned from theexecuteQuery
method of JDBCStatement
objects.java.sql.ResultSet result = statement.executeQuery("SELECT au_fname, au_lname FROM authors" );
After creating a
ResultSet
object, you can iterate through one row at a time by invoking thenext
method. Thenext
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.