ResultSet

Basic Java
≈ 2 min read

ResultSet is a cursor over result rows

After executeQuery(), JDBC returns a ResultSet. It is not a ready-made list of Java objects. It is a cursor over a tabular result, from which the code reads rows and column values sequentially.

Immediately after creation, the cursor is positioned before the first row. Calling next() moves it forward and returns true if a current row exists.

try (ResultSet result = statement.executeQuery()) {
    while (result.next()) {
        long id = result.getLong("id");
        String name = result.getString("name");

        System.out.println(id + ": " + name);
    }
}

A value can be read by column name or position

Methods such as getString(), getLong(), and getBoolean() accept either a column name or its index. JDBC indexes start at 1. In application code, a name or SQL alias is usually easier to read and depends less on column order in the SELECT list.

SQL NULL requires attention

For reference values, a getter may return null. But methods that return primitives cannot do that: for example, getInt() returns 0 for SQL NULL. If the distinction matters, use wasNull() after reading the value.

int age = result.getInt("age");
Integer value = result.wasNull() ? null : age;
ResultSet must be closed too. It is tied to JDBC driver and database resources, so it is convenient to open it in its own try-with-resources.