Junior — Middle
Can you explain how the ResultSet object is implemented and how it functions to retrieve data from the database?
sobes.tech AI
Answer from AI
ResultSet in Java is an interface that represents a table of data obtained as a result of executing an SQL query via JDBC.
How it works:
- After executing a query through a
StatementorPreparedStatementobject, theexecuteQuery()method is called, which returns aResultSet. ResultSetcontains a cursor that initially points before the first row of the result.- To iterate over the data, the
next()method is used, which moves the cursor to the next row and returnstrueif the row exists. - To retrieve values from the current row, methods like
getString(),getInt(),getDate(), etc., are used, specifying the column name or index.
Example:
ResultSet rs = statement.executeQuery("SELECT id, name FROM users");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
// process data
}
Thus, ResultSet provides sequential access to the rows of the SQL query result and allows extracting data by columns.