Sobes.tech
Junior

What is the role of the ResultSet object in working with databases using JDBC?

sobes.tech AI

Answer from AI

The ResultSet object represents a tabular view of data obtained as a result of executing an SQL query. It allows iterating over the rows of this result and retrieving column values for each row.

Main functions:

  • Data access: Allows retrieving values from the fields (columns) of the current row using various get<DataType>() methods (e.g., getInt(), getString(), getDate()).
  • Iteration: Provides methods to move through the result rows (next(), previous(), first(), last(), absolute()).
  • Metadata information: Through the getMetaData() method, you can obtain a ResultSetMetaData object — which provides information about the structure of the ResultSet, such as the number of columns, their types, names, etc.
  • Data updating: Depending on the ResultSet type and driver capabilities, it may support methods for updating, inserting, or deleting rows directly in the result (e.g., updateRow(), insertRow(), deleteRow()).

Lifecycle:

  1. ResultSet is created after executing an SQL query by a Statement or PreparedStatement object.
  2. It is used to process data.
  3. After completing work, the ResultSet should be closed to free database resources. This can be done explicitly with the close() method or using try-with-resources.
// Example of using ResultSet
import java.sql.*;

public class ResultSetExample {

    public static void main(String[] args) {
        String dbUrl = "jdbc:mysql://localhost:3306/mydatabase"; // Database URL
        String user = "myuser"; // Database user
        String password = "mypassword"; // User password

        String sql = "SELECT id, name, age FROM employees"; // Example SQL SELECT query

        try (Connection conn = DriverManager.getConnection(dbUrl, user, password); // Establish connection
             Statement stmt = conn.createStatement(); // Create Statement object
             ResultSet rs = stmt.executeQuery(sql)) { // Execute query and get ResultSet

            // Iterate over ResultSet rows
            while (rs.next()) {
                int id = rs.getInt("id"); // Get value from "id" column
                String name = rs.getString("name"); // Get value from "name" column
                int age = rs.getInt("age"); // Get value from "age" column

                System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age); // Output data
            }

        } catch (SQLException e) {
            e.printStackTrace(); // Error handling
        }
    }
}
What is the role of the ResultSet object in working… - sobes.tech