How do I move to absolute or relative row?

Category: java.sql, viewed: 2K time(s).

In this example we are showing you how to use result set abosule() and relative() method to jump from one result set row to the other. When you pass a positive number as the parameter you'll move from the first record to the last. But if you pass a negative number as parameter you'll move from the last record backward.

package org.kodejava.example.sql;

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

public class MoveAbsoluteOrRelativeExample {
    public static void main(String[] args) throws Exception{
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost/testdb", "root", "");

            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            ResultSet resultSet = statement.executeQuery("SELECT * FROM products");

            //
            // Move to the second row
            //
            resultSet.absolute(2);
            System.out.println("You are now in: " + resultSet.getRow());

            //
            // Move 2 records forward from the current position (fourth row)
            //
            resultSet.relative(2);
            System.out.println("You are now in: " + resultSet.getRow());

            //
            // Move to the last row in the result set
            //
            resultSet.absolute(-1);
            System.out.println("You are now in: " + resultSet.getRow());

            //
            // Move 3 records backward from the current position (second row)
            //
            resultSet.relative(-3);
            System.out.println("You are now in: " + resultSet.getRow());
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }
}