Using Prepared Statements in Java with Examples

8/16/2025

#Using Prepared Statements in Java with Examples

Go Back

Using Prepared Statements in Java with Examples


Introduction

When working with databases in Java, executing SQL queries securely and efficiently is crucial. The PreparedStatement interface in JDBC is a powerful tool that helps developers write parameterized queries, improve performance, and prevent SQL injection attacks. Unlike the Statement interface, PreparedStatements are precompiled by the database, making them faster and more secure.

In this article, we’ll learn how to use PreparedStatement in Java with examples for SELECT, INSERT, UPDATE, and DELETE queries.


#Using Prepared Statements in Java with Examples

Steps to Use PreparedStatement in Java

Step 1: Import Required JDBC Packages

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

Step 2: Establish Database Connection

Connection con = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/testdb", "root", "password");

Step 3: Create a PreparedStatement

PreparedStatement pstmt = con.prepareStatement(
    "INSERT INTO users (id, name) VALUES (?, ?)"
);

Step 4: Set Parameters

pstmt.setInt(1, 1);
pstmt.setString(2, "John");

Step 5: Execute the Query

int rowsInserted = pstmt.executeUpdate();
System.out.println(rowsInserted + " row(s) inserted.");

Step 6: Close Resources

con.close();
pstmt.close();

Examples of PreparedStatement in Java

1. INSERT Example

PreparedStatement pstmt = con.prepareStatement("INSERT INTO users (id, name) VALUES (?, ?)");
pstmt.setInt(1, 2);
pstmt.setString(2, "Alice");
pstmt.executeUpdate();

2. SELECT Example

PreparedStatement pstmt = con.prepareStatement("SELECT * FROM users WHERE id = ?");
pstmt.setInt(1, 1);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
    System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}

3. UPDATE Example

PreparedStatement pstmt = con.prepareStatement("UPDATE users SET name = ? WHERE id = ?");
pstmt.setString(1, "Michael");
pstmt.setInt(2, 1);
pstmt.executeUpdate();

4. DELETE Example

PreparedStatement pstmt = con.prepareStatement("DELETE FROM users WHERE id = ?");
pstmt.setInt(1, 2);
pstmt.executeUpdate();

Advantages of Using PreparedStatement

  • Security: Protects against SQL injection attacks.

  • Performance: Queries are precompiled and reused by the database.

  • Readability: Code is cleaner and easier to maintain.

  • Parameterization: Supports dynamic query execution with placeholders (?).


Complete Example: PreparedStatement in Java

import java.sql.*;

public class PreparedStatementDemo {
    public static void main(String[] args) {
        try {
            // Step 1: Establish Connection
            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/testdb", "root", "password");

            // Step 2: Create PreparedStatement
            PreparedStatement pstmt = con.prepareStatement("INSERT INTO users (id, name) VALUES (?, ?)");

            // Step 3: Set Parameters
            pstmt.setInt(1, 3);
            pstmt.setString(2, "Emma");

            // Step 4: Execute Update
            int rows = pstmt.executeUpdate();
            System.out.println(rows + " row(s) inserted.");

            // Close connection
            pstmt.close();
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Best Practices

  • Always close ResultSet, PreparedStatement, and Connection.

  • Use try-with-resources for automatic resource management.

  • Prefer PreparedStatement over Statement to avoid SQL injection.

  • Use batch processing when inserting/updating multiple records.


Conclusion

Using PreparedStatement in Java is the recommended way to execute SQL queries. It ensures better performance, security, and cleaner code compared to the traditional Statement interface. By following the examples and best practices, you can build efficient and secure database-driven Java applications.


🔑 Target SEO Keywords:
PreparedStatement in Java, JDBC PreparedStatement example, prevent SQL injection Java, Java SQL queries, JDBC tutorial, execute SQL in Java securely.

Table of content