0
0
JavaComparisonBeginner · 4 min read

Statement vs PreparedStatement in Java: Key Differences and Usage

In Java, Statement is used to execute simple SQL queries without parameters, while PreparedStatement allows precompiling SQL with parameters for better performance and security. PreparedStatement helps prevent SQL injection and is preferred for repeated or parameterized queries.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of Statement and PreparedStatement in Java.

FeatureStatementPreparedStatement
PurposeExecute simple SQL queriesExecute parameterized SQL queries
SQL CompilationCompiled every time it runsPrecompiled once, reused multiple times
SecurityVulnerable to SQL injectionPrevents SQL injection by using parameters
PerformanceSlower for repeated queriesFaster for repeated execution
ParametersDoes not support parametersSupports setting parameters dynamically
Use CaseOne-time or simple queriesRepeated or dynamic queries with input
⚖️

Key Differences

Statement is a basic interface used to execute static SQL queries directly. Each time you run a query with Statement, the database parses and compiles the SQL, which can be slow if repeated often.

PreparedStatement is designed for queries that run multiple times with different inputs. It compiles the SQL once and lets you set parameters safely, which improves performance and protects against SQL injection attacks by separating code from data.

While Statement is simpler and useful for quick, one-off queries, PreparedStatement is better for dynamic queries where user input is involved or when the same query runs many times with different values.

⚖️

Code Comparison

java
import java.sql.*;

public class StatementExample {
    public static void main(String[] args) {
        String url = "jdbc:h2:mem:testdb";
        try (Connection conn = DriverManager.getConnection(url);
             Statement stmt = conn.createStatement()) {
            stmt.execute("CREATE TABLE users (id INT, name VARCHAR(100))");
            stmt.execute("INSERT INTO users VALUES (1, 'Alice')");
            stmt.execute("INSERT INTO users VALUES (2, 'Bob')");

            String nameToFind = "Alice";
            String query = "SELECT id, name FROM users WHERE name = '" + nameToFind + "'";
            ResultSet rs = stmt.executeQuery(query);

            while (rs.next()) {
                System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
Output
ID: 1, Name: Alice
↔️

PreparedStatement Equivalent

java
import java.sql.*;

public class PreparedStatementExample {
    public static void main(String[] args) {
        String url = "jdbc:h2:mem:testdb";
        try (Connection conn = DriverManager.getConnection(url);
             Statement stmt = conn.createStatement()) {
            stmt.execute("CREATE TABLE users (id INT, name VARCHAR(100))");
            stmt.execute("INSERT INTO users VALUES (1, 'Alice')");
            stmt.execute("INSERT INTO users VALUES (2, 'Bob')");

            String nameToFind = "Alice";
            String query = "SELECT id, name FROM users WHERE name = ?";
            try (PreparedStatement pstmt = conn.prepareStatement(query)) {
                pstmt.setString(1, nameToFind);
                ResultSet rs = pstmt.executeQuery();

                while (rs.next()) {
                    System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
Output
ID: 1, Name: Alice
🎯

When to Use Which

Choose Statement when you have simple, static SQL queries that run only once or very rarely, and you do not need to insert user input dynamically.

Choose PreparedStatement when you need to run the same query multiple times with different inputs, or when you want to protect your application from SQL injection by safely handling user data.

In general, PreparedStatement is the safer and more efficient choice for most database operations involving parameters.

Key Takeaways

PreparedStatement improves security by preventing SQL injection.
PreparedStatement is faster for repeated queries due to precompilation.
Statement is simpler but less safe and slower for dynamic queries.
Use PreparedStatement for queries with parameters or user input.
Use Statement only for simple, one-time static SQL commands.