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 optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.