Sobes.tech
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:

  1. A Statement or PreparedStatement object is created.
  2. An SQL query is executed using the executeQuery() method. This method returns a ResultSet.
  3. The next() method is used to iterate over the rows of the ResultSet. The next() method returns true if there is a next row and moves the cursor to it.
  4. Access to the column values of the current row is done using get<type>() methods, such as getString(), 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