To fetch results using a ResultSet in Java JDBC, you follow a standard pattern of executing a query, iterating through the rows, and extracting data using “getter” methods.
Basic Fetching Pattern
- Execute the Query: Use
stmt.executeQuery(sql)(forStatement) orpstmt.executeQuery()(forPreparedStatement). - Iterate through Rows: Use a
while (rs.next())loop. Thenext()method moves the cursor to the next row and returnsfalsewhen there are no more rows. - Retrieve Values: Use methods like
getString(),getInt(),getLong(), orgetBigDecimal()based on the column type.
Example
try (Connection conn = DriverManager.getConnection(url, user, pass);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, created_at FROM users")) {
while (rs.next()) {
// 1. Fetch by Column Name (Recommended for readability)
int id = rs.getInt("id");
String name = rs.getString("name");
// 2. Fetch by Column Index (1-based, often faster)
java.sql.Timestamp date = rs.getTimestamp(3);
System.out.println("User: " + id + " | Name: " + name);
}
} catch (SQLException e) {
e.printStackTrace();
}
Key Considerations
- 1-Based Indexing: If you use column indices (e.g.,
rs.getString(1)), remember that JDBC indices start at 1, not 0. - Column Names vs. Indices:
- Names: More maintainable and easier to read.
- Indices: Slightly better performance as the driver doesn’t have to look up the column mapping.
- Try-with-Resources: Always wrap the
ResultSetin a try-with-resources block (or ensure it is closed in afinallyblock) to prevent database cursor leaks. - Data Types: Use the getter that matches your database schema:
rs.getInt()forINTEGERrs.getString()forVARCHAR/TEXTrs.getBigDecimal()forDECIMAL/NUMERIC(best for currency)rs.getBoolean()forBIT/BOOLEAN
- Handling Nulls: If a column allows
NULL, primitive getters (likegetInt) will return0. To check if the value was actuallynullin the database, callrs.wasNull()immediately after the getter.
