This section describes how to loop through a ResultSet object returned by the executeQuery() method.
Another test I did on SQL Server with JDBC-ODBC Bridge was to loop through
a ResultSet object returned from a query statement. Each ResultSet object has
an internal pointer to indicate the current row from which get*() methods can
retrieve column values.
The next() method on the ResultSet object can be used to move the internal pointer
one row to another in the result set.
The tutorial Java program below shows you how to loop through the ResultSet
to list customer names in Customer table:
/**
* OdbcSqlServerLoopResultSet.java
* Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
*/
import java.sql.*;
public class OdbcSqlServerLoopResultSet {
public static void main(String [] args) {
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(
"jdbc:odbc:SQL_SERVER;user=sa;password=HerongYang;"
+"database=AdventureWorksLT");
// Looping through each row
Statement sta = con.createStatement();
ResultSet res = sta.executeQuery(
"SELECT TOP 10 * FROM SalesLT.Customer");
System.out.println("Customers:");
while (res.next()) {
String firstName = res.getString("FirstName");
String lastName = res.getString("LastName");
System.out.println(" "+firstName+" "+lastName);
}
res.close();
sta.close();
con.close();
} catch (Exception e) {
System.err.println("Exception: "+e.getMessage());
}
}
}
Here is the output of the program:
Customers:
Orlando Gee
Keith Harris
Donna Carreras
Janet Gates
Lucy Harrington
Rosmarie Carroll
Dominic Gash
Kathleen Garza
Katherine Harding
Johnny Caprio