JDBC ResultSet Interface


The ResultSet interface within java.sql functions to store query results from databases when executing commands like SELECT statements. The ResultSet functions as a cursor that points to a single data row and enables extracting values from columns.


Key Responsibilities

  • Hold tabular data returned from queries
  • Navigate rows using a cursor
  • Fetch values from every column within the active row.

Package

import java.sql.ResultSet; 

Syntax

Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");

Methods of ResultSet

Method Description
next() Moves the cursor to the next row
previous() Moves to the previous row
first() Moves to the first row
last() Moves to the last row
absolute(int row) Moves to a specific row
beforeFirst() Moves to before the first row
afterLast() Moves to after the last row
isBeforeFirst() Checks if before first row
isAfterLast() Checks if after last row

Example

import java.sql.*;

public class ResultSetExample {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/testdb", "root", "password");

            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM employees");

            // Process result set
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                double salary = rs.getDouble("salary");

                System.out.println(id + " - " + name + " - " + salary);
            }

            rs.close();
            stmt.close();
            con.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
} 

Best Practices

  • Always close ResultSet after use.
  • Use column names for clarity and maintainability.
  • Scrollable and updatable SQL types require additional memory resources and processing power.



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.