Java Statement executeQuery()

In this guide, you will learn about the Statement executeQuery() method in Java programming and how to use it with an example.

1. Statement executeQuery() Method Overview

Definition:

The executeQuery() method of the Statement interface is used to execute SQL SELECT queries against the database. It returns a ResultSet object that contains the data produced by the query, typically this will be the result of a SQL SELECT statement.

Syntax:

ResultSet executeQuery(String sql) throws SQLException

Parameters:

- sql: a SQL SELECT query.

Key Points:

- The executeQuery() method is primarily used for executing SELECT queries.

- The method returns a ResultSet object, which contains the data retrieved from the database.

- It throws an SQLException if a database access error occurs or the given SQL statement produces anything other than a single ResultSet object.

2. Statement executeQuery() Method Example

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

public class ExecuteQueryExample {

    public static void main(String[] args) {

        String url = "jdbc:your_database_url";
        String user = "your_database_user";
        String password = "your_database_password";

        String sql = "SELECT * FROM employees";

        try (Connection connection = DriverManager.getConnection(url, user, password);
             Statement statement = connection.createStatement()) {

            // Execute the SELECT query and retrieve the result set
            ResultSet resultSet = statement.executeQuery(sql);

            // Process the result set
            while (resultSet.next()) {
                int employeeId = resultSet.getInt("employee_id");
                String firstName = resultSet.getString("first_name");
                String lastName = resultSet.getString("last_name");
                System.out.println("Employee ID: " + employeeId + ", First Name: " + firstName + ", Last Name: " + lastName);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Output:

Employee ID: 1, First Name: John, Last Name: Doe
Employee ID: 2, First Name: Jane, Last Name: Smith
// ... additional results ...

Explanation:

In this example, we connect to a database and create a Statement object. Using this object, we call the executeQuery() method with an SQL SELECT query as its parameter to retrieve data from the employees table. The resulting ResultSet object is then iterated over to print out the employee details.

Comments