How do I move cursor to the last record?

To move the cursor to the end of result set (after the last record) you can call the afterLast() method of the result set.

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 ScrollableAfterLastExample {
    public static void main(String[] args) throws Exception {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost/testdb", "root", "");

            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,

            ResultSet resultSet = statement.executeQuery("SELECT * FROM products");

            // Let's jump to the last records. The afterLast() method will position
            // the cursor after the last record.

            while (resultSet.previous()) {
                String productCode = resultSet.getString("product_code");
                String productName = resultSet.getString("product_name");
                int quantity = resultSet.getInt("quantity");
                double price = resultSet.getDouble("price");

                System.out.println(productCode + "t" + productName + "t" + quantity + "t" + price);
        } catch (SQLException e) {
        } finally {
            if (connection != null) {


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply