← Back to Chapters

JDBC ResultSet

? JDBC ResultSet

? Quick Overview

ResultSet is a core interface in JDBC used to store and manipulate data retrieved from a database. It represents a table of data generated by executing a SQL query using a Statement or PreparedStatement.

? Key Concepts

  • Cursor-based navigation through database records
  • Read-only or updatable result sets
  • Forward-only or scrollable movement
  • Column access using index or name

? Interactive Simulator

Click the button to simulate the cursor moving through the ResultSet.

DATABASE TABLE
ID Name Dept
101 Alice IT
102 Bob HR
103 Charlie Sales
104 Diana Admin
// Java Console Output
ResultSet initialized. Cursor is before first row.

? Syntax / Theory

A ResultSet object is obtained after executing a SQL query. The cursor initially points before the first row and moves row by row using next().

? View Code Example
// Executing SELECT query to obtain ResultSet
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students");

? Code Example(s)

? View Code Example
// Reading data from ResultSet using while loop
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + " " + name);
}

? Live Output / Explanation

Explanation

Each call to rs.next() moves the cursor to the next row. Column values are accessed using getter methods like getInt() and getString().

✅ Tips & Best Practices

  • Always close ResultSet, Statement, and Connection
  • Use column names instead of indexes for clarity
  • Prefer PreparedStatement for performance and security
  • Handle SQLException properly

? Try It Yourself

  1. Create a table in your database
  2. Insert multiple records
  3. Fetch data using ResultSet
  4. Print values using column names