Skip to content
C

ResultSet

ResultSet represents the table of data returned after running a SQL query, like a SELECT statement. It lets you move through the returned rows and read column values one at a time.


1. What is ResultSet?

ResultSet represents the table of data returned after running a SQL query, like a SELECT statement. It lets you move through the returned rows and read column values one at a time.

2. Why is it used?

After running a query, you need a way to actually access and use the returned data. ResultSet provides this row-by-row access to the results, along with methods to read specific columns by name or position.

3. Real-Life Example

Think of receiving a printed report after submitting a request, with each row representing one record, and columns holding specific details. ResultSet is how a Java program reads through this "report" one row at a time.

4. Syntax

java
ResultSet rs = statement.executeQuery("SELECT * FROM table"); while (rs.next()) { String value = rs.getString("columnName"); }

5. Example Program

java
import java.sql.*; public class ResultSetDemo { public static void main(String[] args) throws SQLException { Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/schooldb", "root", "password" ); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT name, age FROM students"); while (rs.next()) { System.out.println(rs.getString("name") + " - " + rs.getInt("age")); } conn.close(); } }

Output:

Aditi - 21
Rohan - 22

(Actual output depends on the real data present in the students table.)

6. Key Points to Remember

  • rs.next() moves the cursor to the next row and returns false once there are no more rows.
  • Column values can be retrieved using column names (getString("name")) or column index positions.
  • The cursor initially starts before the first row, so next() must be called at least once before reading any data.