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.
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 StatementPreparedStatement?
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 prepareThresholduseServerPrepStmts=false
| Method | Since | Use |
|---|---|---|
setStringsetIntsetLongsetBigDecimal | JDBC 1 | Typed values; indexes start at 1 |
setNull(index, Types.X) | JDBC 1 | SQL NULL |
setObjectLocalDateOffsetDateTime | JDBC 4.2 (Java 8) | Dates and times without java.sql.Date |
setBytessetBinaryStream | JDBC 1 / 4.0 | Binary data |
clearParameters | JDBC 1 | Forget all values set so far |
getParameterMetaData | JDBC 3.0 | The number and types of the placeholders |
addBatchexecuteBatch | JDBC 2.0 | Many executions in one round trip; see |
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
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 ?anything' OR '1'='1
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:
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
. Because... AND email = 'anything' OR '1'='1' binds tighter thanAND , 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.OR - With the
, 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.PreparedStatement - 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 NULLIN
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:
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
plusprepareStatement(sql, Statement.RETURN_GENERATED_KEYS) returns the database-generated id, 4, without a second query.getGeneratedKeys() stores SQLsetNull(4, Types.INTEGER) . ButNULL with aWHERE age = ? parameter matched nothing, because in SQL,NULL is unknown rather than true. Searching for missing values needsNULL = NULL , which found both users without an age.IS NULL- A placeholder stands for exactly one value, so an
list needs oneIN 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.
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:
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
reported the type the database expects for each of the six placeholders, fromgetParameterMetaData() toUUID . Not every driver can supply this before execution, but where it works it is handy for generic tools.CHARACTER VARYING with asetObject and anLocalDate stored them without conversion throughOffsetDateTime orjava.sql.Date , and the offsetTimestamp came back unchanged. The old+02:00 converts through the JVM's default time zone, a common source of times that are off by some hours.setTimestamp keptsetBigDecimal exact, and1999.90 stored the two bytessetBytes . For large files,0xCA 0xFE streams the data instead of holding it all in a byte array.setBinaryStream gave asetNull(6, Types.VARCHAR) note, read back as JavaNULL .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
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:
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
wasminAge , so the previous value 25 was used again and the result was stillnull instead of all three users. Always set every parameter on every execution, as the[ben] fix does.setNull makes forgotten parameters fail loudly with "Parameter "#2" is not set".clearParameters() 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_ , and onlyESCAPE '!' matched.100%_real- Parameter indexes start at 1.
threw an exception with H2's codesetInt(0, ...) .90008 - A
in aNULL list makes the condition unknown for every row, soNOT IN returned no rows at all, whileage NOT IN (34, NULL) returned ben. FilterNOT IN (34, 99) s out of lists before binding them.null
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 PreparedStatementPreparedStatement
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:
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
also costs a round trip, which dwarfs these numbers. For bulk inserts, combine a reused statement withexecuteUpdate andaddBatch , as shown on theexecuteBatchtransactions and batch page . Connection pools such asHikariCP rely on the driver for statement caching.
Choosing how to pass values
| Situation | Use |
|---|---|
| Any value from users, files or other systems | A ? |
| Money and exact decimals | setBigDecimal |
| Dates and times | setObjectLocalDateLocalDateTimeOffsetDateTime |
| Nullable values | setNull(index, Types.X)setObject(index, null, Types.X)IS NULL |
| A list of values | One ? |
| Search text with LIKE | Escape %_ESCAPE |
| User-chosen column or sort order | A fixed allow-list of names in code |
| The same SQL many times | One statement, reused, with every parameter set each time |
| Thousands of rows | Reused statement plus addBatch |
For connections, result sets and error codes, see