0
0
JavaConceptBeginner · 3 min read

What is PreparedStatement in Java: Explanation and Example

PreparedStatement in Java is a feature that lets you write SQL queries with placeholders and fill in values later. It helps prevent SQL injection and improves performance by pre-compiling the SQL statement.
⚙️

How It Works

Imagine you want to send a letter but leave some blanks to fill in later, like the recipient's name or address. PreparedStatement works similarly for SQL queries. You write the query with placeholders (like question marks), and then you fill in the blanks with actual values before running it.

This approach lets the database prepare the query once and reuse it with different values, making it faster. It also protects your program from harmful inputs by treating the values safely, so attackers can't trick your database with bad commands.

💻

Example

This example shows how to use PreparedStatement to insert a user into a database safely.

java
import java.sql.*;

public class PreparedStatementExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/mydb";
        String user = "root";
        String password = "password";

        String sql = "INSERT INTO users (name, email) VALUES (?, ?)";

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

            pstmt.setString(1, "Alice");
            pstmt.setString(2, "alice@example.com");

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

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
Output
1 row(s) inserted.
🎯

When to Use

Use PreparedStatement whenever you need to run SQL queries that include user input or variable data. It is especially useful when:

  • You want to protect your application from SQL injection attacks.
  • You need to run the same query multiple times with different values efficiently.
  • You want clearer and easier-to-maintain code by separating SQL logic from data.

For example, in web applications where users submit forms, PreparedStatement safely inserts or updates data in the database.

Key Points

  • PreparedStatement pre-compiles SQL queries with placeholders.
  • It improves performance by reusing the compiled query.
  • It prevents SQL injection by safely handling input values.
  • It makes code cleaner and easier to read.

Key Takeaways

PreparedStatement lets you write SQL queries with placeholders and fill values safely.
It protects your database from SQL injection attacks.
It improves performance by pre-compiling and reusing queries.
Use it whenever your SQL query includes user input or variable data.
PreparedStatement makes your code cleaner and more secure.