ResultSet
The result of a SELECT query: a cursor that walks through the rows one by one.
Available since: Java 1.1
Syntax
public interface ResultSet extends AutoCloseableExamples
Result rows into a list of records. next() moves to the next row and returns false when there are no more rows:
import java.sql.*;
record Product(int id, String title, double price) {}
void main() throws SQLException {
try (Connection conn = DriverManager.getConnection("jdbc:sqlite::memory:");
Statement st = conn.createStatement()) {
st.executeUpdate("CREATE TABLE products (id INTEGER, title TEXT, price REAL)");
st.executeUpdate("INSERT INTO products VALUES (1, 'Tea', 3.5), (2, 'Coffee', 4.2)");
List<Product> products = new ArrayList<>();
try (ResultSet rs = st.executeQuery("SELECT id, title, price FROM products ORDER BY id")) {
while (rs.next()) {
products.add(new Product(rs.getInt("id"), rs.getString("title"), rs.getDouble("price")));
}
}
products.forEach(IO::println);
}
}Output:
Product[id=1, title=Tea, price=3.5]
Product[id=2, title=Coffee, price=4.2]getInt() returns 0 for NULL. wasNull() and getObject(), which returns null, tell them apart:
import java.sql.*;
void main() throws SQLException {
try (Connection conn = DriverManager.getConnection("jdbc:sqlite::memory:");
Statement st = conn.createStatement()) {
st.executeUpdate("CREATE TABLE users (name TEXT, age INTEGER)");
st.executeUpdate("INSERT INTO users VALUES ('Anna', NULL)");
try (ResultSet rs = st.executeQuery("SELECT age FROM users")) {
rs.next();
IO.println(rs.getInt("age"));
IO.println(rs.wasNull());
IO.println(rs.getObject("age"));
}
}
}Output:
0
true
nullNotes
The cursor starts before the first row, so next() is called before reading data. Columns are read by name (getString("title")) or by number starting at 1. By default the cursor moves forward only. A ResultSet is closed together with its Statement, but closing it explicitly with try is more reliable. Dates are read with getObject(column, LocalDate.class).
See also
- PreparedStatement — A precompiled SQL query with ? parameters. Protects against SQL injection.
- DriverManager.getConnection() — Opens a connection to a database by its JDBC URL.
- record — Declares a record — an immutable data class with ready-made equals(), hashCode() and toString().
Related recipes
In the tutorial
- JDBC basics — Working with a database from Java through JDBC — what a driver is, connecting with DriverManager.getConnection, Statement for SQL commands and reading rows with ResultSet, using SQLite.