ResultSet in JDBC

JDBC (Java Database Connectivity) ResultSet is an essential interface that represents the result set of a database query. It allows Java programs to retrieve data from a relational database, typically after executing a SQL query.

Following are some key points about ResultSet:

Retrieves Database Data

A ResultSet object acts as a container for the data retrieved from a database query. It provides methods to access and manipulate this data row by row.

Scrollable and Read-Only

ResultSets can be scrollable, which means we can move forward and backward through the result set, or they can be forward-only, allowing traversal only in one direction. Most result sets are read-only, meaning we can’t update the data in the database through the ResultSet.

Iterative Access

We typically access the data in a ResultSet using a loop, iterating through each row and extracting the desired columns’ values.

Closed After Use

Once we’re done using a ResultSet, it should be explicitly closed to release the associated database resources.

Following is a simplified example of using a ResultSet in JDBC to retrieve data from a hypothetical “employees” table:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ResultSetExample {
    public static void main(String[] args) {
        try {
            // Loading the JDBC Driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Establish a database connection
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");

            // Create a SQL statement
            Statement statement = connection.createStatement();

            // Execute a SQL query
            String sqlQuery = "SELECT * FROM employees";
            ResultSet resultSet = statement.executeQuery(sqlQuery);

            // Iterate through the result set and print employee names
            while (resultSet.next()) {
                String employeeName = resultSet.getString("employee_name");
                System.out.println("Employee Name: " + employeeName);
            }

            // Close the ResultSet, Statement, and Connection
            resultSet.close();
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments