Junior — Middle
Explain the concept of Result Set in JDBC and how it is used when working with databases
sobes.tech AI
Answer from AI
In JDBC, ResultSet is an object that contains the results of executing an SQL query against a database, typically a SELECT statement. It represents a table of data retrieved from the database and allows programmatic navigation through this data and extraction of values.
Key points of using ResultSet:
- After executing a query via Statement or PreparedStatement, the executeQuery() method is called, which returns a ResultSet.
- ResultSet supports a cursor, initially positioned before the first row. To move to the next row, the next() method is called.
- To retrieve data from the current row, methods like getInt(), getString(), getDate(), etc., are used, specifying the column name or index.
- ResultSet can be used for reading data row by row and processing it in the application.
Example:
String sql = "SELECT id, name FROM users";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("User: " + id + ", " + name);
}
rs.close();
stmt.close();
Thus, ResultSet is the main way to retrieve and process data from a database in Java via JDBC.