Junior
What is ResultSet in JDBC?
sobes.tech AI
Answer from AI
The ResultSet interface provides access to tabular data obtained as a result of executing an SQL query. It acts as an iterator over the result rows.
Main features of ResultSet:
- Moving through rows:
next(),previous(),first(),last(),absolute(),relative(). - Reading data from columns:
getString(),getInt(),getDouble(),getObject(), and others, by column index or name. - Updating data in the current row (for updatable
ResultSet). - Retrieving metadata about the result (
ResultSetMetaData).
A typical ResultSet processing loop:
// Assuming statement is a Statement or PreparedStatement
try (ResultSet resultSet = statement.executeQuery("SELECT id, name FROM users")) {
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("User ID: " + id + ", Name: " + name);
}
} catch (SQLException e) {
e.printStackTrace();
}
It is important to properly close the ResultSet (using try-with-resources or a finally block) to free database resources.