Java ResultSet next()

In this guide, you will learn about the ResultSet next() method in Java programming and how to use it with an example.

1. ResultSet next() Method Overview

Definition:

The next() method of the java.sql.ResultSet interface moves the cursor forward one row from its current position in the ResultSet object. It is primarily used to iterate over the rows returned by an SQL query.

Syntax:

boolean next() throws SQLException

Parameters:

The method does not take any parameters.

Key Points:

- A ResultSet object initially has its cursor positioned before the first row. The next() method is called to make the first row the current row and return true if a row exists, and false if there are no more rows.

- If next() returns true, the cursor moves to the next row, making it the current row, and the method can be called repeatedly to iterate through the result set.

- If next() returns false, the cursor is positioned after the last row, and further invocations will keep returning false.

- A SQLException will be thrown if a database access error occurs or this method is called on a closed result set.

2. ResultSet next() Method Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ResultSetNextExample {
    public static void main(String[] args) {
        String jdbcUrl = "jdbc:mysql://localhost:3306/testdb";
        String jdbcUsername = "root";
        String jdbcPassword = "password";

        String query = "SELECT id, name FROM users";

        try (Connection connection = DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(query)) {

            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                System.out.println("ID: " + id + ", Name: " + name);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

ID: 1, Name: John Doe
ID: 2, Name: Jane Doe
... (other rows from the 'users' table)

Explanation:

In this example, we established a JDBC connection to a MySQL database and executed a SQL query to retrieve id and name columns from the users table. 

The next() method of the ResultSet interface was used to move the cursor forward one row at a time, and for each row in the result set, the id and name were retrieved and printed to the console. 

The loop continued until the next() returned false, indicating that there were no more rows in the result set.

Comments