Junior
What is a ResultSet and how is it used in Java?
sobes.tech AI
Answer from AI
ResultSet represents a set of data obtained as a result of executing an SQL query on a database. It provides methods for iterating over rows and accessing column values in each row.
It is used as follows:
- A
StatementorPreparedStatementobject is created. - An SQL query is executed using the
executeQuery()method. This method returns aResultSet. - The
next()method is used to iterate over the rows of theResultSet. Thenext()method returnstrueif there is a next row and moves the cursor to it. - Access to the column values of the current row is done using
get<type>()methods, such asgetString(),getInt(),getDouble(), etc., specifying the column name or index.
Example of usage:
// Create Statement
Statement stmt = connection.createStatement();
// Execute query
ResultSet rs = stmt.executeQuery("SELECT id, name, age FROM users");
// Iterate over results
while (rs.next()) {
// Get column values
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
// Output data
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
// Close ResultSet, Statement, and Connection in a finally block to free resources