✅ 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 studentsStores 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
trueif a row is available.Returns
falsewhen 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 |
|---|---|
| Moves cursor to next row |
| Gets integer value from that column |
| Gets string value from that column |
| Closes the ResultSet |
🛡️ Best Practices
✅ Always close
ResultSetafter you're done:rs.close();✅ Use
PreparedStatementinstead of plainStatementfor security✅ Handle exceptions using
try-catch❌ Don’t forget to close your
ConnectionandStatementtoo.
🧠 Summary
Feature | Description |
|---|---|
| Object that holds data from a |
Cursor | Moves row by row using |
Getters | Use |
Looping | Use |
Close It | Free memory by closing the |