Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

JDBC · Lesson 6

Handling ResultSet

Reading Query Results

A ResultSet is a cursor over rows returned by a query. The cursor begins before the first row, and next() advances it while reporting whether a row exists. Mapping each column to a meaningful Java value keeps database code explicit and testable.

Iterating Through Rows

Read columns by name when clarity matters and use the appropriate getter for each SQL type. The result set, statement, and connection should all be closed reliably.

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class CourseRepository {
    public void printPublishedCourses(Connection connection) throws Exception {
        String sql = "SELECT id, title, lesson_count FROM courses WHERE published = ?";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setBoolean(1, true);
            try (ResultSet results = statement.executeQuery()) {
                while (results.next()) {
                    long courseId = results.getLong("id");
                    String courseTitle = results.getString("title");
                    int lessonCount = results.getInt("lesson_count");
                    System.out.println(courseId + ": " + courseTitle + " (" + lessonCount + ")");
                }
            }
        }
    }
}

ResultSet Features

FeatureMeaningExample
CursorCurrent row positionresults.next()
GetterConverts a column valuegetString("title")
wasNull()Detects SQL NULL after a getterOptional nullable field
MetadataDescribes columnsDynamic tools and diagnostics

Common Mistake and Practices

Common Mistake: Calling getString before next(), or assuming a nullable column always contains a value. Both mistakes can produce invalid reads or misleading domain objects.

  • Advance the cursor before reading.
  • Prefer column labels over fragile numeric positions.
  • Handle SQL NULL explicitly.
  • Map rows into domain objects near the repository boundary.
  • Close results and statements with try-with-resources.

Real-World Use Case

A course catalog repository turns each ResultSet row into a CourseSummary object. The service layer receives typed objects rather than knowing column names or cursor details.

Quiz Check

Quick Knowledge Test

Loading quiz questions...