Java Connection prepareStatement()

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

1. Connection prepareStatement() Method Overview

Definition:

The prepareStatement() method of the Connection interface creates a PreparedStatement object for sending parameterized SQL queries to the database. The SQL statement provided to the method may have one or more ? IN parameter placeholders.

Syntax:

PreparedStatement prepareStatement(String sql) throws SQLException

Parameters:

- sql: a SQL statement that may contain one or more ? IN parameter placeholders.

Key Points:

- The prepareStatement() method is used to create PreparedStatement objects.

- PreparedStatement objects can perform precompilation and DB-side caching of the SQL statement, which leads to improved performance.

- The method throws a SQLException if a database access error occurs.

- The SQL statement provided may include placeholders for parameters, which can be set using various setXxx() methods in the PreparedStatement interface.

2. Connection prepareStatement() Method Example

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

public class PrepareStatementExample {

    public static void main(String[] args) {

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

        String sql = "INSERT INTO employees (first_name, last_name) VALUES (?, ?)";

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

            // Setting the values for the placeholders in the SQL query
            preparedStatement.setString(1, "John");
            preparedStatement.setString(2, "Doe");

            int rowsAffected = preparedStatement.executeUpdate();
            System.out.println("Rows affected: " + rowsAffected);

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

Output:

Rows affected: 1

Explanation:

In this example, a connection to the database is established using the DriverManager::getConnection() method. Then, the Connection::prepareStatement() method is used to create a PreparedStatement object with a SQL insert statement. 

The placeholders in the SQL statement are replaced with actual values using the setString() method of the PreparedStatement object. 

Finally, the executeUpdate() method is called to execute the SQL insert statement, and the number of affected rows is printed to the console.

Comments