Sobes.tech
Junior

What is ResultSet in Java?

sobes.tech AI

Answer from AI

The java.sql.ResultSet interface represents a table of data obtained as a result of executing an SQL query. It provides methods for navigating through the rows of the table and retrieving the values of individual columns of the current row by column name or index.

Key features:

  • Navigation: Supports moving through the result set (forward, backward, skipping, etc., depending on the cursor type).
  • Data access: Allows retrieving data of various types (strings, numbers, dates, BLOB/CLOB, etc.) from columns.
  • Resource management: Requires closing (close()) to free database resources.
  • Types: Can be scrollable and/or updatable, which is determined when creating the Statement.

Main loop for processing ResultSet:

// Example of obtaining a ResultSet
try (Statement stmt = connection.createStatement();
     ResultSet rs = stmt.executeQuery("SELECT id, name FROM users")) {

    while (rs.next()) { // Move to the next row
        int id = rs.getInt("id"); // Get value by column name
        String name = rs.getString(2); // Get value by column index (index starts at 1)

        System.out.println("ID: " + id + ", Name: " + name);
    }
} catch (SQLException e) {
    e.printStackTrace();
}

Cursor types:

Type Properties
TYPE_FORWARD_ONLY Forward only.
TYPE_SCROLL_INSENSITIVE Scroll forward/backward, not sensitive to database changes after obtaining the ResultSet.
TYPE_SCROLL_SENSITIVE Scroll forward/backward, sensitive to database changes after obtaining the ResultSet.

Update modes:

Mode Properties
CONCUR_READ_ONLY Read-only, cannot modify data.
CONCUR_UPDATABLE Can modify data through the ResultSet.
What is ResultSet in Java? — Java - sobes.tech