Sobes.tech
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. Returns true if the row exists, false otherwise.
  • getXxx(int columnIndex): Returns the value of the column by index (starting from 1), where Xxx is 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 the ResultSet.

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();
What is the purpose of ResultSet in Java? — Java - sobes.tech