Junior
What is the purpose of ResultSet in Java?
sobes.tech AI
Answer from AI
Used to represent data from a database obtained after executing an SQL query. It allows iterating over the result rows and retrieving column values for each row.
Main methods:
next(): Moves the cursor to the next row. Returnstrueif the row exists,falseotherwise.getXxx(int columnIndex): Returns the value of the column by index (starting from 1), whereXxxis the data type (e.g.,getInt,getString,getDate).getXxx(String columnLabel): Returns the value of the column by label (column name).close(): Releases resources associated with theResultSet.
Example of usage:
// assuming connection and statement are already created
String sql = "SELECT id, name FROM users";
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
rs.close();