PreparedStatement & SQL Injection Prevention

A PreparedStatement sends SQL with ? placeholders and passes the values separately as typed data. That one design choice stops SQL injection and lets the database reuse its work. This page explains how prepared statements work, then runs injection attacks, typed parameters, the traps that placeholders do not prevent, and a speed comparison on an in-memory H2 database.

Share

Contents

What a PreparedStatement is

A database runs SQL in stages: it parses the text, checks the tables and columns, plans how to execute the query, and then runs the plan. With a plain Statement, the values are part of the SQL text, so every different value is a different SQL string that goes through every stage. A PreparedStatement is created from SQL with ? placeholders. The SQL text stays fixed, and the values are sent separately, as typed data.

That separation gives two benefits. The first is security: a value can never change the structure of the query, which makes SQL injection impossible for anything passed as a parameter. The second is speed: the database or the driver can parse and plan the fixed SQL once and reuse the result. How much is reused depends on the driver. The PostgreSQL driver switches to a server-side prepared statement after a statement has run 5 times (its prepareThreshold setting), while MySQL Connector/J by default substitutes the values on the client (useServerPrepStmts=false) and still sends them safely escaped.

The PreparedStatement methods used most
MethodSinceUse
setString, setInt, setLong, setBigDecimalJDBC 1Typed values; indexes start at 1
setNull(index, Types.X)JDBC 1SQL NULL with its type
setObject with LocalDate, OffsetDateTimeJDBC 4.2 (Java 8)Dates and times without java.sql.Date
setBytes, setBinaryStreamJDBC 1 / 4.0Binary data
clearParametersJDBC 1Forget all values set so far
getParameterMetaDataJDBC 3.0The number and types of the placeholders
addBatch, executeBatchJDBC 2.0Many executions in one round trip; see batches

Each example opens an in-memory H2 2.3 database on JDK 21 with three users, using the helper below. One user has no age, so NULL handling can be tested.

Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

// A fresh in-memory database with a users table for each example
final class Db {
    private Db() {
    }

    static Connection open(String name) throws SQLException {
        Connection c = DriverManager.getConnection("jdbc:h2:mem:" + name, "sa", "");
        try (Statement st = c.createStatement()) {
            st.execute("CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, "
                    + "name VARCHAR(40), email VARCHAR(60), role VARCHAR(10), age INT)");
            st.execute("INSERT INTO users (name, email, role, age) VALUES "
                    + "('ana', 'ana@x.io', 'admin', 34), ('ben', 'ben@x.io', 'user', 28), "
                    + "('cho', 'cho@x.io', 'user', NULL)");
        }
        return c;
    }
}

SQL injection, and why PreparedStatement stops it

The two login methods run the same query. The first builds the SQL text by concatenating the inputs; the second uses ? placeholders. The program calls both with honest input, then with the classic attack anything' OR '1'='1 as the email, and finally with a legitimate name that contains an apostrophe.

Java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class Injection {

    // Vulnerable: the input becomes part of the SQL text
    static int loginConcat(Connection c, String name, String email) throws Exception {
        String sql = "SELECT COUNT(*) FROM users WHERE name = '" + name
                + "' AND email = '" + email + "'";
        try (Statement st = c.createStatement(); ResultSet rs = st.executeQuery(sql)) {
            rs.next();
            return rs.getInt(1);
        }
    }

    // Safe: the SQL text is fixed and the input is sent separately as data
    static int loginPrepared(Connection c, String name, String email) throws Exception {
        String sql = "SELECT COUNT(*) FROM users WHERE name = ? AND email = ?";
        try (PreparedStatement ps = c.prepareStatement(sql)) {
            ps.setString(1, name);
            ps.setString(2, email);
            try (ResultSet rs = ps.executeQuery()) {
                rs.next();
                return rs.getInt(1);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        try (Connection c = Db.open("inj")) {
            String attack = "anything' OR '1'='1";
            System.out.println("honest login, concatenated:   "
                    + loginConcat(c, "ana", "ana@x.io"));
            System.out.println("attack, concatenated:         " + loginConcat(c, "ana", attack));
            System.out.println("attack, PreparedStatement:    " + loginPrepared(c, "ana", attack));

            // A name with an apostrophe is a normal value for a PreparedStatement...
            try (PreparedStatement ps = c.prepareStatement(
                    "INSERT INTO users (name, email, role) VALUES (?, ?, 'user')")) {
                ps.setString(1, "O'Brien");
                ps.setString(2, "ob@x.io");
                ps.executeUpdate();
            }
            System.out.println("O'Brien via PreparedStatement: "
                    + loginPrepared(c, "O'Brien", "ob@x.io"));
            // ...but breaks the concatenated query
            try {
                loginConcat(c, "O'Brien", "ob@x.io");
            } catch (Exception e) {
                System.out.println("O'Brien concatenated:          "
                        + e.getClass().getSimpleName());
            }
        }
    }
}

Output:

Output
honest login, concatenated:   1
attack, concatenated:         3
attack, PreparedStatement:    0
O'Brien via PreparedStatement: 1
O'Brien concatenated:          JdbcSQLSyntaxErrorException
  • With concatenation, the attack produced the SQL ... AND email = 'anything' OR '1'='1'. Because AND binds tighter than OR, the condition is true for every row, and the "login" matched all 3 users without a valid email. In a real login, this is an authentication bypass.
  • With the PreparedStatement, the same input matched 0 rows. The database compiled the query with placeholders first and then received the input as a plain string value, which cannot change the query's structure.
  • The name O'Brien worked as a parameter but broke the concatenated query with a syntax error. Injection-prone code is also simply buggy for ordinary data.

Escaping quotes by hand is not a fix: the rules differ between databases and character sets, and getting them slightly wrong reopens the hole. Use placeholders for every value that comes from outside the code.

Generated keys, NULL, IN lists and identifiers

The second program covers four details that come up in almost every data access layer: getting the id generated by an insert, passing NULL, building an IN list, and trying to use a placeholder for a column name.

Java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Parameters {

    public static void main(String[] args) throws Exception {
        try (Connection c = Db.open("params")) {
            // Generated keys: get the AUTO_INCREMENT id of the new row
            try (PreparedStatement ps = c.prepareStatement(
                    "INSERT INTO users (name, email, role, age) VALUES (?, ?, ?, ?)",
                    Statement.RETURN_GENERATED_KEYS)) {
                ps.setString(1, "dev");
                ps.setString(2, "dev@x.io");
                ps.setString(3, "user");
                ps.setNull(4, Types.INTEGER);                    // explicit SQL NULL
                ps.executeUpdate();
                try (ResultSet keys = ps.getGeneratedKeys()) {
                    keys.next();
                    System.out.println("new user id: " + keys.getInt(1));
                }
            }

            // "= ?" never matches NULL, because NULL = NULL is not true in SQL
            try (PreparedStatement ps = c.prepareStatement(
                    "SELECT COUNT(*) FROM users WHERE age = ?")) {
                ps.setNull(1, Types.INTEGER);
                try (ResultSet rs = ps.executeQuery()) {
                    rs.next();
                    System.out.println("age = NULL matches: " + rs.getInt(1) + " rows");
                }
            }
            try (Statement st = c.createStatement(); ResultSet rs = st.executeQuery(
                    "SELECT COUNT(*) FROM users WHERE age IS NULL")) {
                rs.next();
                System.out.println("age IS NULL matches: " + rs.getInt(1) + " rows");
            }

            // IN lists: one placeholder per value
            List<String> wanted = List.of("ana", "cho", "nobody");
            String sql = "SELECT name FROM users WHERE name IN ("
                    + String.join(",", Collections.nCopies(wanted.size(), "?"))
                    + ") ORDER BY name";
            List<String> found = new ArrayList<>();
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                for (int i = 0; i < wanted.size(); i++) {
                    ps.setString(i + 1, wanted.get(i));
                }
                try (ResultSet rs = ps.executeQuery()) {
                    while (rs.next()) {
                        found.add(rs.getString(1));
                    }
                }
            }
            System.out.println(sql + " -> " + found);

            // Placeholders are for values only, not for table or column names
            try (PreparedStatement ps = c.prepareStatement("SELECT name FROM users ORDER BY ?")) {
                ps.setString(1, "age");
                ps.executeQuery();
            } catch (SQLException e) {
                System.out.println("ORDER BY ? with \"age\": " + e.getClass().getSimpleName()
                        + ", SQLState " + e.getSQLState());
            }
        }
    }
}

Output:

Output
new user id: 4
age = NULL matches: 0 rows
age IS NULL matches: 2 rows
SELECT name FROM users WHERE name IN (?,?,?) ORDER BY name -> [ana, cho]
ORDER BY ? with "age": JdbcSQLDataException, SQLState 22018
  • prepareStatement(sql, Statement.RETURN_GENERATED_KEYS) plus getGeneratedKeys() returns the database-generated id, 4, without a second query.
  • setNull(4, Types.INTEGER) stores SQL NULL. But WHERE age = ? with a NULL parameter matched nothing, because in SQL, NULL = NULL is unknown rather than true. Searching for missing values needs IS NULL, which found both users without an age.
  • A placeholder stands for exactly one value, so an IN list needs one ? per element. The SQL text then varies with the list size; databases such as PostgreSQL also accept a single array parameter with = ANY(?).
  • Placeholders cannot replace identifiers such as column or table names. H2 tried to use the string "age" as a column position and failed with a data conversion error. Depending on the database, the same mistake either fails like this or runs while sorting by a constant, which has no effect. For a user-chosen sort column, map the input to a fixed list of allowed column names in code.

Typed parameters: decimals, dates, UUIDs and bytes

Every value should be sent with a setter that matches its column type, so the driver does not have to guess. The payment table has one column each of the types that cause the most conversion trouble: a UUID key, an exact decimal, a date, a timestamp with an offset, binary data and a nullable text column.

Java
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Types;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.UUID;

public class TypedParameters {

    public static void main(String[] args) throws Exception {
        try (Connection c = DriverManager.getConnection("jdbc:h2:mem:typed", "sa", "");
             Statement st = c.createStatement()) {
            st.execute("""
                    CREATE TABLE payment (id UUID PRIMARY KEY, amount DECIMAL(12,2),
                      due DATE, paid_at TIMESTAMP WITH TIME ZONE, receipt VARBINARY(16),
                      note VARCHAR(40))""");

            UUID id = UUID.fromString("123e4567-e89b-12d3-a456-426614174000");
            String insert = "INSERT INTO payment VALUES (?, ?, ?, ?, ?, ?)";
            try (PreparedStatement ps = c.prepareStatement(insert)) {
                ParameterMetaData pmd = ps.getParameterMetaData();
                System.out.print("parameter types:");
                for (int i = 1; i <= pmd.getParameterCount(); i++) {
                    System.out.print(" " + pmd.getParameterTypeName(i));
                }
                System.out.println();

                ps.setObject(1, id);                                    // UUID
                ps.setBigDecimal(2, new BigDecimal("1999.90"));
                ps.setObject(3, LocalDate.of(2026, 4, 30));             // java.time (JDBC 4.2)
                ps.setObject(4, OffsetDateTime.parse("2026-04-02T10:15:00+02:00"));
                ps.setBytes(5, new byte[] {(byte) 0xCA, (byte) 0xFE});
                ps.setNull(6, Types.VARCHAR);
                System.out.println("inserted: " + ps.executeUpdate());
            }

            try (PreparedStatement ps = c.prepareStatement(
                    "SELECT amount, due, paid_at, receipt, note FROM payment WHERE id = ?")) {
                ps.setObject(1, id);
                try (ResultSet rs = ps.executeQuery()) {
                    rs.next();
                    System.out.println("amount  " + rs.getBigDecimal(1));
                    System.out.println("due     " + rs.getObject(2, LocalDate.class));
                    System.out.println("paid_at " + rs.getObject(3, OffsetDateTime.class));
                    System.out.println("receipt " + rs.getBytes(4).length + " bytes, first 0x"
                            + Integer.toHexString(rs.getBytes(4)[0] & 0xFF));
                    System.out.println("note    " + rs.getString(5));
                }
            }
        }
    }
}

Output:

Output
parameter types: UUID DECIMAL DATE TIMESTAMP WITH TIME ZONE BINARY VARYING CHARACTER VARYING
inserted: 1
amount  1999.90
due     2026-04-30
paid_at 2026-04-02T10:15+02:00
receipt 2 bytes, first 0xca
note    null
  • getParameterMetaData() reported the type the database expects for each of the six placeholders, from UUID to CHARACTER VARYING. Not every driver can supply this before execution, but where it works it is handy for generic tools.
  • setObject with a LocalDate and an OffsetDateTime stored them without conversion through java.sql.Date or Timestamp, and the offset +02:00 came back unchanged. The old setTimestamp converts through the JVM's default time zone, a common source of times that are off by some hours.
  • setBigDecimal kept 1999.90 exact, and setBytes stored the two bytes 0xCA 0xFE. For large files, setBinaryStream streams the data instead of holding it all in a byte array.
  • setNull(6, Types.VARCHAR) gave a NULL note, read back as Java null.

Traps with parameters

A placeholder protects the query's structure, but it does not make every query correct. The program adds a user called 100%_real, whose name contains both LIKE wildcards, and shows four mistakes that compile and run without complaint until the data is wrong.

Java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class Pitfalls {

    static List<String> names(PreparedStatement ps) throws SQLException {
        List<String> out = new ArrayList<>();
        try (ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                out.add(rs.getString(1));
            }
        }
        return out;
    }

    static String escapeLike(String s) {
        return s.replace("!", "!!").replace("%", "!%").replace("_", "!_");
    }

    public static void main(String[] args) throws Exception {
        try (Connection c = Db.open("pit")) {
            try (PreparedStatement add = c.prepareStatement(
                    "INSERT INTO users (name, email, role) VALUES (?, ?, 'user')")) {
                add.setString(1, "100%_real");
                add.setString(2, "r@x.io");
                add.executeUpdate();
            }

            // 1. Parameters stay set between executions
            try (PreparedStatement ps = c.prepareStatement(
                    "SELECT name FROM users WHERE role = ? AND (? IS NULL OR age > ?)"
                    + " ORDER BY name")) {
                for (Integer minAge : new Integer[] {25, null}) {
                    ps.setString(1, "user");
                    if (minAge != null) {                // bug: nothing is set for null
                        ps.setInt(2, minAge);
                        ps.setInt(3, minAge);
                    }
                    System.out.println("users, minAge=" + minAge + ":       " + names(ps));
                }
                ps.setNull(2, java.sql.Types.INTEGER);   // the fix: always set every parameter
                ps.setNull(3, java.sql.Types.INTEGER);
                System.out.println("users, setNull:           " + names(ps));
                ps.clearParameters();
                ps.setString(1, "user");
                try {
                    names(ps);
                } catch (SQLException e) {
                    System.out.println("after clearParameters:    " + e.getMessage()
                            .substring(0, e.getMessage().indexOf(';')));
                }
            }

            // 2. LIKE wildcards inside a parameter are still wildcards
            try (PreparedStatement ps = c.prepareStatement(
                    "SELECT name FROM users WHERE name LIKE ? ORDER BY name")) {
                ps.setString(1, "%" + "_" + "%");        // user typed "_" into a search box
                System.out.println("LIKE '%_%' (unescaped):   " + names(ps));
            }
            try (PreparedStatement ps = c.prepareStatement(
                    "SELECT name FROM users WHERE name LIKE ? ESCAPE '!' ORDER BY name")) {
                ps.setString(1, "%" + escapeLike("_") + "%");
                System.out.println("LIKE '%!_%' ESCAPE '!':   " + names(ps));
            }

            // 3. Indexes start at 1
            try (PreparedStatement ps = c.prepareStatement("SELECT name FROM users WHERE id = ?")) {
                ps.setInt(0, 1);
            } catch (SQLException e) {
                System.out.println("setInt(0, ...):           " + e.getMessage().lines()
                        .findFirst().orElse(""));
            }

            // 4. A NULL in NOT IN removes every row
            try (PreparedStatement ps = c.prepareStatement(
                    "SELECT name FROM users WHERE age NOT IN (?, ?) ORDER BY name")) {
                ps.setInt(1, 34);
                ps.setNull(2, java.sql.Types.INTEGER);
                System.out.println("age NOT IN (34, NULL):    " + names(ps));
                ps.setInt(2, 99);
                System.out.println("age NOT IN (34, 99):      " + names(ps));
            }
        }
    }
}

Output:

Output
users, minAge=25:       [ben]
users, minAge=null:       [ben]
users, setNull:           [100%_real, ben, cho]
after clearParameters:    Parameter "#2" is not set
LIKE '%_%' (unescaped):   [100%_real, ana, ben, cho]
LIKE '%!_%' ESCAPE '!':   [100%_real]
setInt(0, ...):           Invalid value "0" for parameter "parameterIndex" [90008-232]
age NOT IN (34, NULL):    []
age NOT IN (34, 99):      [ben]
  • Parameter values stay set after execution. The loop meant "no age filter" on its second pass, but the code set nothing when minAge was null, so the previous value 25 was used again and the result was still [ben] instead of all three users. Always set every parameter on every execution, as the setNull fix does. clearParameters() makes forgotten parameters fail loudly with "Parameter "#2" is not set".
  • % and _ inside a parameter are still LIKE wildcards. A search for _ matched every user, because _ means "any one character". Escape the wildcards in the value and declare the escape character with ESCAPE '!', and only 100%_real matched.
  • Parameter indexes start at 1. setInt(0, ...) threw an exception with H2's code 90008.
  • A NULL in a NOT IN list makes the condition unknown for every row, so age NOT IN (34, NULL) returned no rows at all, while NOT IN (34, 99) returned ben. Filter nulls out of lists before binding them.

How much faster is reusing a PreparedStatement?

To see what parsing costs, the program inserts 20,000 rows three ways: with concatenated SQL text, with a new PreparedStatement per row, and with one PreparedStatement reused for all rows. Each variant runs 4 times; the first is a warm-up and the best of the other 3 is shown. This is a rough comparison on a 2-CPU Linux machine with JDK 21 and in-memory H2, with no network involved.

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

public class Speed {

    interface Task {
        void run(Connection c) throws SQLException;
    }

    static final int N = 20000;
    static final String INSERT = "INSERT INTO item (id, name, price) VALUES (?, ?, ?)";

    static long bestOf3(Connection c, Task task) throws SQLException {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 4; run++) {                   // run 0 is a warm-up
            try (Statement st = c.createStatement()) {
                st.execute("TRUNCATE TABLE item");
            }
            long t0 = System.nanoTime();
            task.run(c);
            long t = System.nanoTime() - t0;
            if (run > 0) {
                best = Math.min(best, t);
            }
        }
        return best / 1000000;
    }

    public static void main(String[] args) throws Exception {
        try (Connection c = DriverManager.getConnection("jdbc:h2:mem:speed", "sa", "")) {
            try (Statement st = c.createStatement()) {
                st.execute("CREATE TABLE item (id INT PRIMARY KEY, name VARCHAR(20),"
                        + " price DECIMAL(10,2))");
            }
            long concat = bestOf3(c, conn -> {
                try (Statement st = conn.createStatement()) {
                    for (int i = 0; i < N; i++) {
                        st.executeUpdate("INSERT INTO item (id, name, price) VALUES (" + i
                                + ", 'item" + i + "', " + (i % 100) + ".99)");
                    }
                }
            });
            long preparedEachTime = bestOf3(c, conn -> {
                for (int i = 0; i < N; i++) {
                    try (PreparedStatement ps = conn.prepareStatement(INSERT)) {
                        ps.setInt(1, i);
                        ps.setString(2, "item" + i);
                        ps.setBigDecimal(3, java.math.BigDecimal.valueOf(i % 100 * 100 + 99, 2));
                        ps.executeUpdate();
                    }
                }
            });
            long preparedOnce = bestOf3(c, conn -> {
                try (PreparedStatement ps = conn.prepareStatement(INSERT)) {
                    for (int i = 0; i < N; i++) {
                        ps.setInt(1, i);
                        ps.setString(2, "item" + i);
                        ps.setBigDecimal(3, java.math.BigDecimal.valueOf(i % 100 * 100 + 99, 2));
                        ps.executeUpdate();
                    }
                }
            });
            System.out.printf("%,d inserts into in-memory H2, best of 3 runs%n", N);
            System.out.printf("Statement, SQL text concatenated:  %4d ms%n", concat);
            System.out.printf("new PreparedStatement per row:     %4d ms%n", preparedEachTime);
            System.out.printf("one PreparedStatement, reused:     %4d ms%n", preparedOnce);
        }
    }
}

Output of the insert timing run:

Output
20,000 inserts into in-memory H2, best of 3 runs
Statement, SQL text concatenated:   161 ms
new PreparedStatement per row:       59 ms
one PreparedStatement, reused:       41 ms
  • Reusing one prepared statement was the fastest, two to five times faster than concatenated SQL across runs on this machine. Each of the 20,000 concatenated strings is a new statement the database must parse and plan.
  • Preparing a new statement for every row came in between. H2 keeps a small per-session cache of recently parsed SQL, which hides part of the cost of preparing the same text again; a database that prepares on the server may also pay an extra round trip for each prepare.
  • With a real database over a network, each executeUpdate also costs a round trip, which dwarfs these numbers. For bulk inserts, combine a reused statement with addBatch and executeBatch, as shown on the transactions and batch page. Connection pools such as HikariCP rely on the driver for statement caching.

Choosing how to pass values

What to use for each kind of value
SituationUse
Any value from users, files or other systemsA ? placeholder, never concatenation
Money and exact decimalssetBigDecimal
Dates and timessetObject with LocalDate, LocalDateTime or OffsetDateTime
Nullable valuessetNull(index, Types.X), or setObject(index, null, Types.X); query with IS NULL
A list of valuesOne ? per element, or an array parameter where the database supports it
Search text with LIKEEscape % and _ in the value and add ESCAPE
User-chosen column or sort orderA fixed allow-list of names in code
The same SQL many timesOne statement, reused, with every parameter set each time
Thousands of rowsReused statement plus addBatch inside a transaction

For connections, result sets and error codes, see JDBC basics.