JAVA - Zero to Hero / JDBC - Java Database Connectivity

ResultSet Handling

✅ What is ResultSet?

In Java, when you use JDBC to connect to a database and run a SELECT query, the data returned by that query is stored in a special object called ResultSet.

👉 ResultSet is like a temporary table in Java that holds rows of data returned from the database.


🔄 How Does ResultSet Work?

When you run a SQL query using Statement or PreparedStatement, you write:

ResultSet rs = statement.executeQuery("SELECT * FROM students");

This line:

  • Runs the query: SELECT * FROM students

  • Stores the results (rows) inside a ResultSet object called rs

Imagine your students table looks like this:

id

name

age

1

Alice

20

2

Bob

21

3

Charlie

19

Now all this data is temporarily held in memory inside rs.


🧭 ResultSet Uses a Cursor

  • A cursor is a pointer that moves row by row inside the ResultSet.

  • Initially, it sits before the first row.

  • You must use rs.next() to move it to the first row.

while (rs.next()) {
    // now pointing to one row
}

Each time you call rs.next():

  • It moves the cursor to the next row.

  • Returns true if a row is available.

  • Returns false when there are no more rows.


🧱 How to Get Column Values

Once the cursor points to a row, you can use getter methods to get the values of that row's columns.

Example:

int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");

You can also use column indexes (starting from 1), but names are safer and easier to read.

int id = rs.getInt(1); // 1st column

🔁 Full Code Example

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, age FROM students");

while (rs.next()) {
    int id = rs.getInt("id");
    String name = rs.getString("name");
    int age = rs.getInt("age");

    System.out.println(id + " " + name + " " + age);
}
1  Alice   20  
2  Bob     21  
3  Charlie 22

⚙️ Common ResultSet Methods

Method

Description

rs.next()

Moves cursor to next row

rs.getInt("column")

Gets integer value from that column

rs.getString("column")

Gets string value from that column

rs.close()

Closes the ResultSet


🛡️ Best Practices

  • ✅ Always close ResultSet after you're done: rs.close();

  • ✅ Use PreparedStatement instead of plain Statement for security

  • ✅ Handle exceptions using try-catch

  • ❌ Don’t forget to close your Connection and Statement too.


🧠 Summary

Feature

Description

ResultSet

Object that holds data from a SELECT query

Cursor

Moves row by row using rs.next()

Getters

Use getInt(), getString() to get column values

Looping

Use while (rs.next()) to loop through all rows

Close It

Free memory by closing the ResultSet when done