Reading a ResultSet row by row
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A shop report prints products, but a query's answer arrives as a table of rows. How does Java walk through those rows and pick out each column?
The cursor and next()
A cursor is the marker of a ResultSet that points at one row at a time; you can only read that row. It starts before the first row, and rs.next() moves it down one row.
List the three subcategories of Electronics and watch where the cursor is.
Example 1 · Watching the cursor move
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class CursorDemo { public static void main(String[] args) throws SQLException { try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "SELECT name FROM categories WHERE parent_id = 1 ORDER BY name")) {
// The cursor starts before the first row, so the first next() moves to row 1 boolean moved = rs.next(); System.out.println("first next() returned " + moved); while (moved) { System.out.println(" on row " + rs.getRow() + ": " + rs.getString("name")); moved = rs.next(); } System.out.println("next() returned false: no more rows"); } }}first next() returned true on row 1: Accessories on row 2: Laptops on row 3: Mobiles next() returned false: no more rows
What this code does
- The first
next()returnstrueand moves the cursor onto row 1.getRow()reports the current row number. - After the third row,
next()returnsfalse; the loop stops and the cursor is now after the last row. - The three subcategories of Electronics (category 1) come back in name order because of
ORDER BY name.
rs.next() returns true if it landed on a row and false when there are no more rows. That is why every reading loop is while (rs.next()) { ... }: the call moves first, then the body reads the row it moved to. Reading row by row lets the same simple loop handle 3 rows or 3 lakh rows.
Predict the output
Where is the cursor?
Electronics (category 1) has three subcategories. Pick what is printed.
Round 1 of 2
The loop counts the rows.
Getters by column label or by index
A column label is the name a column has in the result: its alias if it has one, else its own name. rs.getString("name") reads by label; rs.getString(2) reads by index, counted from 1.
Read the same laptop rows twice, once by column label and once by column index.
Example 2 · Reading by label and by index
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class LabelVsIndexDemo { public static void main(String[] args) throws SQLException { String sql = "SELECT sku, name, price, stock FROM products WHERE category_id = 3 ORDER BY price"; try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); Statement st = con.createStatement()) {
System.out.println("Laptops, read by column label:"); try (ResultSet rs = st.executeQuery(sql)) { while (rs.next()) { String sku = rs.getString("sku"); String name = rs.getString("name"); int stock = rs.getInt("stock"); System.out.println(" " + sku + " | " + name + " | Rs " + rs.getBigDecimal("price") + " | " + stock + " in stock"); } }
System.out.println("The same rows, read by column index (1 = sku, 2 = name ...):"); try (ResultSet rs = st.executeQuery(sql)) { while (rs.next()) { System.out.println(" " + rs.getString(1) + " | " + rs.getString(2) + " | Rs " + rs.getBigDecimal(3) + " | " + rs.getInt(4) + " in stock"); } } } }}Laptops, read by column label: LAP-IPS3 | Lenovo IdeaPad Slim 3 | Rs 42990.00 | 12 in stock LAP-HPV15 | HP Victus 15 Gaming | Rs 64990.00 | 5 in stock The same rows, read by column index (1 = sku, 2 = name ...): LAP-IPS3 | Lenovo IdeaPad Slim 3 | Rs 42990.00 | 12 in stock LAP-HPV15 | HP Victus 15 Gaming | Rs 64990.00 | 5 in stock
What this code does
- Both loops print the same thing. In the second, index 3 is
priceonly because of its place in theSELECTlist. - If someone changes the SQL to
SELECT name, sku, ..., the label version still works; the index version prints the name and SKU swapped. - The same SQL string is run twice. Each run gives a fresh
ResultSetwith its cursor before the first row.
A getter reads one column of the current row as a Java value: getString, getInt, getLong, getBigDecimal, getBoolean and others. Labels are the safer habit because the code says what it reads. Use an index mainly for a single nameless column, such as SELECT COUNT(*).
Labels ignore upper or lower case, so getString("NAME") also works. Pick the getter that matches the column type; the Type Mapping lesson maps every MySQL type to its getter.
Column aliases and joined queries
An alias is a new column name given with AS in the SELECT, for example p.name AS product_name. The label JDBC uses is the alias, so you read rs.getString("product_name").
Join products to categories, where both have a column called name, then fix it with aliases.
Example 3 · Two columns called name, and the fix with aliases
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class AliasJoinDemo { public static void main(String[] args) throws SQLException { try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); Statement st = con.createStatement()) {
// Trap: both tables have a column called name String noAliases = "SELECT p.name, c.name FROM products p " + "JOIN categories c ON c.category_id = p.category_id WHERE p.product_id = 9"; try (ResultSet rs = st.executeQuery(noAliases)) { rs.next(); System.out.println("Without aliases, getString(\"name\") gives: " + rs.getString("name")); System.out.println("The category name is only reachable as column 2: " + rs.getString(2)); }
// Fix: give every column a clear label with AS, then read those labels String withAliases = "SELECT p.name AS product_name, c.name AS category_name, " + "o.unit_price * o.quantity AS line_total " + "FROM order_items o " + "JOIN products p ON p.product_id = o.product_id " + "JOIN categories c ON c.category_id = p.category_id " + "WHERE o.order_id = 2 ORDER BY p.name"; try (ResultSet rs = st.executeQuery(withAliases)) { System.out.println("Order 2:"); while (rs.next()) { System.out.println(" " + rs.getString("product_name") + " (" + rs.getString("category_name") + "): Rs " + rs.getBigDecimal("line_total")); } } } }}Without aliases, getString("name") gives: Clean Code
The category name is only reachable as column 2: Books
Order 2:
Atomic Habits (Books): Rs 798.00
Clean Code (Books): Rs 499.00
The Pragmatic Programmer (Books): Rs 650.00What this code does
- Without aliases,
getString("name")returns the firstnamecolumn, the product. The categoryBooksis reachable only as column 2. - With
AS product_name,AS category_nameandAS line_total, each label says exactly what it holds, including the calculated column. line_totalisunit_price * quantityworked out by MySQL: 2 copies of Atomic Habits at Rs 399.00 gives798.00.
Once a column has an alias, its old name no longer works as a label. Computed columns such as o.unit_price * o.quantity or COUNT(*) have no useful name either: give every such column an alias, and the Java code reads like the report it prints.
Fix the error
Fix the column label
Read the real error, then pick the line that fixes it.
Round 1 of 2
The Java code asks for a label the SELECT never produced.
Error
Column 'category_name' not found.
An empty result, and exactly one row
An empty result is a ResultSet with no rows. It is not an error: the first rs.next() returns false, so a while loop runs zero times.
Look up one product by id, then list a category that has no products.
Example 4 · One row with if, and an empty list
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class OneRowDemo { // productId is an int, so it cannot carry quotes or extra SQL into the text static void showProduct(Statement st, int productId) throws SQLException { String sql = "SELECT name, price FROM products WHERE product_id = " + productId; try (ResultSet rs = st.executeQuery(sql)) { if (rs.next()) { System.out.println("Product " + productId + ": " + rs.getString("name") + " at Rs " + rs.getBigDecimal("price")); } else { System.out.println("Product " + productId + ": not found"); } } }
static void listCategory(Statement st, int categoryId) throws SQLException { String sql = "SELECT name FROM products WHERE category_id = " + categoryId + " ORDER BY name"; try (ResultSet rs = st.executeQuery(sql)) { int count = 0; while (rs.next()) { count++; System.out.println(" " + rs.getString("name")); } if (count == 0) { System.out.println(" (no products in category " + categoryId + ")"); } } }
public static void main(String[] args) throws SQLException { try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); Statement st = con.createStatement()) { showProduct(st, 3); showProduct(st, 99);
System.out.println("Category 6:"); listCategory(st, 6); System.out.println("Category 1:"); listCategory(st, 1); } }}Product 3: iPhone 15 128GB at Rs 69900.00 Product 99: not found Category 6: Cotton Kurta Running Shoes Category 1: (no products in category 1)
What this code does
showProductusesif (rs.next()): product 3 exists, product 99 does not, and theelsebranch printsnot foundinstead of throwing.listCategorycounts rows inside the loop. Category 1 (Electronics) holds no products directly, only subcategories, so the count stays 0 and the message prints.
Use if (rs.next()) instead of while when a query can return at most one row, such as a lookup by primary key. Aggregates like SELECT COUNT(*) always return exactly one row, so one rs.next() is enough there.
The value in the WHERE of this example is an int parameter joined with +. A Java int can only hold digits, so it cannot break the SQL. Text values still wait for prepared statements.
'Column not found' and 'Before start of result set'
Four mistakes run in a row, each with a fresh ResultSet, and the program prints the exact message the driver gives.
Example 5 · The four common ResultSet errors
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class ResultSetErrorsDemo { public static void main(String[] args) throws SQLException { String sql = "SELECT sku, name FROM products WHERE category_id = 5 ORDER BY sku"; try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); Statement st = con.createStatement()) {
try (ResultSet rs = st.executeQuery(sql)) { System.out.println(rs.getString("name")); } catch (SQLException e) { System.out.println("1. " + e.getMessage()); }
try (ResultSet rs = st.executeQuery(sql)) { rs.next(); System.out.println(rs.getBigDecimal("price")); } catch (SQLException e) { System.out.println("2. " + e.getMessage()); }
try (ResultSet rs = st.executeQuery(sql)) { rs.next(); System.out.println(rs.getString(0)); } catch (SQLException e) { System.out.println("3. " + e.getMessage()); }
try (ResultSet rs = st.executeQuery(sql)) { while (rs.next()) { // count or print rows here } System.out.println(rs.getString("sku")); } catch (SQLException e) { System.out.println("4. " + e.getMessage()); } } }}1. Before start of result set 2. Column 'price' not found. 3. Column Index out of range, 0 < 1. 4. After end of result set
What this code does
- Mistake 1 reads before
next(). Mistake 2 asks forprice, which theSELECTdid not include. Mistake 3 uses index 0. Mistake 4 reads after the loop has moved past the last row. - Each mistake gets a fresh
ResultSet, so one failure does not hide the next. These are the exact messages of MySQL Connector/J.
These messages come from the MySQL driver and happen in Java, after the query itself has worked. Read the message, then check where the cursor is and which labels the SELECT actually produced:
Before start of result set: callrs.next()(orif (rs.next())) before reading.Column 'price' not found.: fix theSELECTor the label; an alias replaces the old name.Column Index out of range, 0 < 1.: indexes start at 1. An index larger than the column count gives the same error.After end of result set: read inside the loop, not afternext()has returnedfalse.
Find the bug
Which line throws?
Tap the line that throws the error named in the prompt.
Before start of result set
next() gives Illegal operation on empty result set. instead. Same mistake, same fix.Next step
Check your understanding
12 quick questions