Nearby lessons
13 of 37JDBC - The ResultSet
- The difference between Select and Non-Select operations
- executeQuery vs executeUpdate — when to use which
- Reading results with the ResultSet methods
- Complete CRUD programs: Insert, Select, Update, Delete
- The ResultSet object and how it works
The ResultSet is a fundamental part of database programming with JDBC. This lesson explains The ResultSet — How to Read It, ResultSet Types — How You Can Move Through Rows and Program: a scrollable ResultSet in action with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
The ResultSet — How to Read It
A ResultSet is the object that holds the rows returned by a SELECT. Think of it as a table with a cursor that starts before the first row:
- rs.next() — moves the cursor to the next row. Returns false when there are no more rows.
- rs.getInt(columnNumber) / rs.getString(columnNumber) — read a value by column position (starts at 1).
- rs.getInt("columnName") — read a value by column name (cleaner).
Common getXXX methods: getInt, getString, getDouble, getFloat, getLong, getBoolean, getDate, getTimestamp, getObject.
ResultSet Types — How You Can Move Through Rows
By default, a ResultSet can only move forward (rs.next()). JDBC supports three types and two concurrency modes:
| ResultSet type | What it allows |
|---|---|
| TYPE_FORWARD_ONLY | Only forward movement (default) |
| TYPE_SCROLL_INSENSITIVE | Move forward AND backward; does not see changes made by others |
| TYPE_SCROLL_SENSITIVE | Scrollable; sees changes made by others (rarely used) |
| Concurrency | What it allows |
|---|---|
| CONCUR_READ_ONLY | Only reading (default) |
| CONCUR_UPDATABLE | Can update rows through the ResultSet |
Program: a scrollable ResultSet in action
Scrollable ResultSet methods: first(), last(), absolute(n), relative(n), previous(), beforeFirst(), afterLast().
- Select ops (SELECT) use executeQuery() → ResultSet.
- Non-select ops (INSERT/UPDATE/DELETE) use executeUpdate() → row count.
- rs.next() moves the cursor; getInt/getString/getDouble read values.
- CRUD = Create(INSERT), Retrieve(SELECT), Update, Delete.
- Always close the connection after work.
- Use PreparedStatement for real applications (SQL injection safety).