Java PreparedStatement executeQuery()

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

1. PreparedStatement executeQuery() Method Overview

Definition:

The executeQuery() method of the PreparedStatement interface is used to execute SQL queries against the database. It is typically utilized for SQL SELECT queries where data is retrieved from the database.

Syntax:

ResultSet executeQuery() throws SQLException

Parameters:

The method does not take any parameters.

Key Points:

- The executeQuery() method returns a ResultSet object which holds the data retrieved from the database.

- It is mainly used for executing SELECT queries.

- It throws a SQLException if a database access error occurs, or the SQL statement does not return a ResultSet object.

2. PreparedStatement executeQuery() Method Example

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

public class ExecuteQueryExample {

    public static void main(String[] args) {

        String url = "jdbc:mysql://localhost:3306/mysql_database";
        String user = "root";
        String password = "root";

        String sql = "SELECT * FROM employees WHERE department_id = ?";

        try (Connection connection = DriverManager.getConnection(url, user, password);
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

            // Set the value for the placeholder in the SQL query
            preparedStatement.setInt(1, 101);

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

            // 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 use the executeQuery() method to retrieve data from the employees table where the department_id is 101. We set the value for the department_id placeholder using the setInt() method of the PreparedStatement interface. The executeQuery() method is then called to execute the SELECT query, and the resulting data is printed to the console.

Comments