JDBC Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 2.11

Looping through ResultSet with res.next()

This section describes how to loop through ResultSet objects with the res.next() method.

If the returning ResultSet Object of a query statement contains multiple rows, you can use res.next() method to loop through each row in the output.

The tutorial Java program below shows you how to loop through the ResultSet to list customer names in Customer table:

/**
 * LoopResultSet.java
 * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
 */
import java.sql.*;
public class LoopResultSet {
  public static void main(String [] args) {
    Connection con = null;
    try {

// Load Microsoft JDBC Driver 1.0
      Class.forName(
        "com.microsoft.sqlserver.jdbc.SQLServerDriver");

// Obtaining a connection to SQL Server
      con = DriverManager.getConnection(
          "jdbc:sqlserver://localhost:1269;"
        + "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);
      }

      con.close();        
    } catch (java.lang.ClassNotFoundException e) {
      System.err.println("ClassNotFoundException: "
        +e.getMessage());
    } catch (SQLException e) {
      System.err.println("SQLException: "
        +e.getMessage());
    }
  }
}

If you run this program, you will get something like:

Customers
   Orlando Gee
   Keith Harris
   Donna Carreras
   Janet Gates
   Lucy Harrington
   Rosmarie Carroll
   Dominic Gash
   Kathleen Garza
   Katherine Harding
   Johnny Caprio

Sections in This Chapter

Commonly Used JDBC Class Methods

Calling createStatement() and executeQuery

Receiving ResultSet Objects from executeQuery

Closing ResultSet Objects - res.close()

Looping through ResultSet with res.next()

Retrieving Field Values using res.get*() Methods

Using ResultSetMetaData Objects to List All Fields

Dr. Herong Yang, updated in 2007
Looping through ResultSet with res.next()