Prepared Statements in JDBC: Parameters, Reuse and Preventing SQL Injection
Use PreparedStatement for every SQL statement with variable values: ? placeholders and setter methods, reuse and statement caching, dates, NULLs, IN lists and LIKE patterns, how SQL injection works and why parameters stop it, whitelisting identifiers, and the enquote helpers.
kvi5hnuCode Sprout team member12 min readOn this page
Real queries depend on values that are only known at run time: the product a user searched for, the customer who is logged in, a price limit from a form. Pasting such values into an SQL string is the most common security mistake in database programming. JDBC's answer is the PreparedStatement. You write the SQL once with ? placeholders and supply the values separately. This is safer and often faster, and the code becomes simpler too.
Placeholders and setters
String sql = "SELECT name, price FROM products WHERE supplier_id = ? AND price < ? ORDER BY price";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, "NORD");
ps.setBigDecimal(2, new BigDecimal("100"));
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) { ... }
}
}
- Each
?is a parameter (the SQL standard calls it a host variable). Parameters are numbered from 1, in the order they appear in the SQL. - Setters exist for every type, matching the
ResultSetgetters:setInt,setLong,setString,setBigDecimal,setBoolean,setBytes, and so on.setObject(index, value)lets the driver choose the type. For dates and times,setObject(index, localDate)is the modern way (JDBC 4.2). - Run it with
executeQuery(),executeUpdate()orexecute(), the versions without an SQL argument.
A prepared statement can be executed many times. Parameters keep their values between executions, so you only set the ones that change. clearParameters() resets them all, and executing with an unset parameter fails (SQLState 90012 in H2, 07001 or similar elsewhere).
NULL parameters
To pass SQL NULL, call setNull(index, Types.VARCHAR) (with the column's type), or setObject(index, null), which most drivers accept. Remember that WHERE supplier_id = ? with a NULL parameter never matches, because a comparison with NULL is unknown (article 57). If the value may be NULL, write WHERE supplier_id IS NOT DISTINCT FROM ?, which is standard SQL, supported by PostgreSQL and H2 among others. With other databases, use (supplier_id = ? OR (? IS NULL AND supplier_id IS NULL)), binding the value twice.
SQL injection
Suppose a login check builds its SQL by concatenation:
String sql = "SELECT name FROM users WHERE name = '" + name + "' AND password_hash = '" + hash + "'";
What if someone enters the user name nobody' OR 1=1 --? The statement becomes
SELECT name FROM users WHERE name = 'nobody' OR 1=1 --' AND password_hash = '...'
The quote in the input ended the string literal. OR 1=1 makes the condition true for every row, and -- turns the password check into a comment. Every user comes back, and the program logs the attacker in as the first one. With ada' -- as the name, the attacker logs in as ada without knowing that account's password. Depending on the database and driver settings, input like x'; DROP TABLE users; -- can even run a second statement.
That is SQL injection: input that changes the structure of a statement rather than just supplying a value. It has caused countless data breaches and is still near the top of the OWASP lists of web application risks. It doesn't just affect login forms. Any value from a request, a file, a message queue or even another database table that ends up in SQL text can be an attack.
With a prepared statement, the SQL text is fixed before any input is seen:
PreparedStatement ps = conn.prepareStatement("SELECT name FROM users WHERE name = ? AND password_hash = ?");
ps.setString(1, name);
ps.setString(2, hash);
The driver sends the values separately from the SQL, or encodes them correctly, so they can only ever be values. With the input nobody' OR 1=1 --, the database simply looks for a user with that odd name and finds none. Here are both versions run against H2 (the full program is at the end of this article):
--- string concatenation ---
SELECT name FROM users WHERE name = 'nobody' OR 1=1 --' AND password_hash = 'wrong'
logged in as ada
logged in as bob
SELECT name FROM users WHERE name = 'ada' --' AND password_hash = 'wrong'
logged in as ada
--- prepared statement ---
nobody' OR 1=1 -- -> no match
ada' -- -> no match
ada -> logged in as ada
Many frameworks build SQL for you: JPA, Spring's JdbcClient, jOOQ and MyBatis with #{}. They use prepared statements underneath and are safe as long as you use their parameter mechanisms. Each also has a way to insert raw SQL (such as JPA native queries built by concatenation, or MyBatis ${}), and the same rule applies there.
Parameters only work for values
A placeholder stands for a value. It can't replace a table or column name, a keyword such as ASC, or a list. With H2, SELECT name FROM ? is a syntax error. ORDER BY ? binds a value, not a column name, so it either sorts by a constant, which does nothing, or fails, as it does in H2. When parts of the SQL structure must vary:
- Identifiers and sort orders: map the user's choice to SQL text you wrote yourself, using a whitelist such as
Map.of("price", "p.price", "newest", "p.added DESC"), and reject everything else. - IN lists: generate exactly as many placeholders as there are values,
IN (?, ?, ?), and bind each one. Some databases (PostgreSQL, H2) also accept= ANY(?)with a single array parameter created byconn.createArrayOf("VARCHAR", values). An empty list needs special handling, becauseIN ()is invalid SQL. - Optional filters: append
AND column = ?fragments only for the filters that are present, and collect the values in a list to bind in the same order. - LIKE searches: the pattern is a value, so bind it. But
%and_in the user's input are wildcards inside the pattern, so a search for "100%" would match every name containing "100", and a search for "%" every name at all. Escape them, and declare the escape character:name LIKE ? ESCAPE '!'with!%and!_in the value.
JDBC 4.3 (Java 9) added quoting helpers as default methods of Statement: enquoteLiteral (doubles quotes and adds the surrounding ones), enquoteIdentifier (adds double quotes where needed), isSimpleIdentifier and enquoteNCharLiteral. Drivers may override them for their database's rules. They are useful for generating DDL or scripts, but for values, parameters remain the right tool.
Performance: preparing and caching
When a database runs a statement, it parses the SQL and works out an execution plan, which costs time. With a prepared statement, the SQL text is the same for every execution, so the database (or the driver) can reuse the plan. Databases also cache plans for identical SQL text across statements, which concatenated SQL with ever-changing literals defeats.
You don't need to keep PreparedStatement objects around yourself. A prepared statement belongs to its connection and becomes unusable when the connection closes. Drivers and pools can cache statements per connection. For example, the PostgreSQL driver switches to a server-side prepared statement after the same SQL has run five times (its prepareThreshold), and Oracle and MySQL drivers have statement cache settings. Just call prepareStatement where you need it, and let the infrastructure do the caching.
getParameterMetaData() reports how many parameters a statement has and, if the driver knows, their SQL types.
Trying it with H2
This program creates a users and a products table, then runs the login check both ways. It reuses a prepared query with changing parameters, inserts a row with a LocalDate and a NULL, compares = ? and IS NOT DISTINCT FROM ? with a NULL parameter, and builds an IN list with generated placeholders and with = ANY(?). It also escapes a LIKE pattern, tries to parameterize ORDER BY and a table name, and reads parameter metadata:
import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDate;
import java.util.*;
public class Prepared {
public static void main(String[] args) throws SQLException {
try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:shop")) {
try (Statement stat = conn.createStatement()) {
stat.executeUpdate("CREATE TABLE users (name VARCHAR(20) PRIMARY KEY, password_hash VARCHAR(64), admin BOOLEAN)");
stat.executeUpdate("INSERT INTO users VALUES ('ada', 'x1', TRUE), ('bob', 'x2', FALSE)");
stat.executeUpdate("CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(40), supplier VARCHAR(10), price DECIMAL(8,2), added DATE)");
stat.executeUpdate("""
INSERT INTO products VALUES (1, 'Hammer', 'ACME', 12.50, DATE '2026-03-01'),
(2, 'Oak shelf', 'NORD', 89.90, DATE '2026-05-17'), (3, 'Pine stool', 'NORD', 35.00, DATE '2026-06-02'),
(4, '100% wool rug', 'NORD', 120.00, NULL), (5, 'Desk lamp', 'SOLA', 42.00, DATE '2026-09-30')""");
}
System.out.println("--- string concatenation ---");
String name = "nobody' OR 1=1 --";
String sql = "SELECT name FROM users WHERE name = '" + name + "' AND password_hash = 'wrong'";
System.out.println(sql);
try (Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery(sql)) {
while (rs.next()) System.out.println(" logged in as " + rs.getString(1));
}
name = "ada' --";
sql = "SELECT name FROM users WHERE name = '" + name + "' AND password_hash = 'wrong'";
System.out.println(sql);
try (Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery(sql)) {
while (rs.next()) System.out.println(" logged in as " + rs.getString(1));
}
System.out.println("--- prepared statement ---");
try (PreparedStatement ps = conn.prepareStatement("SELECT name FROM users WHERE name = ? AND password_hash = ?")) {
for (String n : List.of("nobody' OR 1=1 --", "ada' --", "ada")) {
ps.setString(1, n);
ps.setString(2, n.equals("ada") ? "x1" : "wrong");
try (ResultSet rs = ps.executeQuery()) {
System.out.println(n + " -> " + (rs.next() ? "logged in as " + rs.getString(1) : "no match"));
}
}
}
System.out.println("--- reuse: parameters stay bound ---");
try (PreparedStatement ps = conn.prepareStatement("SELECT name, price FROM products WHERE supplier = ? AND price < ? ORDER BY price")) {
ps.setString(1, "NORD");
ps.setBigDecimal(2, new BigDecimal("100"));
print(ps.executeQuery());
ps.setBigDecimal(2, new BigDecimal("50")); // supplier is still NORD
print(ps.executeQuery());
ps.clearParameters();
try { ps.executeQuery(); } catch (SQLException e) { System.out.println(" after clearParameters: " + e.getSQLState()); }
}
System.out.println("--- dates, NULL and setObject ---");
try (PreparedStatement ps = conn.prepareStatement("INSERT INTO products VALUES (?, ?, ?, ?, ?)")) {
ps.setInt(1, 6);
ps.setString(2, "Gift card");
ps.setNull(3, Types.VARCHAR);
ps.setObject(4, new BigDecimal("25.00"));
ps.setObject(5, LocalDate.of(2026, 11, 14));
System.out.println(" inserted " + ps.executeUpdate());
}
try (PreparedStatement ps = conn.prepareStatement("SELECT name FROM products WHERE added >= ? ORDER BY added")) {
ps.setObject(1, LocalDate.of(2026, 6, 1));
print(ps.executeQuery());
}
try (PreparedStatement ps = conn.prepareStatement("SELECT COUNT(*) FROM products WHERE supplier = ?")) {
ps.setNull(1, Types.VARCHAR);
print(ps.executeQuery());
}
try (PreparedStatement ps = conn.prepareStatement("SELECT COUNT(*) FROM products WHERE supplier IS NOT DISTINCT FROM ?")) {
ps.setNull(1, Types.VARCHAR);
print(ps.executeQuery());
}
System.out.println("--- IN lists ---");
List<String> wanted = List.of("ACME", "SOLA");
String placeholders = String.join(", ", Collections.nCopies(wanted.size(), "?"));
try (PreparedStatement ps = conn.prepareStatement("SELECT name FROM products WHERE supplier IN (" + placeholders + ") ORDER BY id")) {
for (int i = 0; i < wanted.size(); i++) ps.setString(i + 1, wanted.get(i));
print(ps.executeQuery());
}
try (PreparedStatement ps = conn.prepareStatement("SELECT name FROM products WHERE supplier = ANY(?) ORDER BY id")) {
ps.setArray(1, conn.createArrayOf("VARCHAR", wanted.toArray()));
print(ps.executeQuery());
}
System.out.println("--- LIKE with user input ---");
String search = "%";
try (PreparedStatement ps = conn.prepareStatement("SELECT name FROM products WHERE name LIKE ? ESCAPE '!' ORDER BY id")) {
ps.setString(1, "%" + search + "%");
System.out.print(" unescaped: "); print(ps.executeQuery());
String escaped = search.replace("!", "!!").replace("%", "!%").replace("_", "!_");
ps.setString(1, "%" + escaped + "%");
System.out.print(" escaped: "); print(ps.executeQuery());
}
System.out.println("--- what can't be a parameter ---");
try (PreparedStatement ps = conn.prepareStatement("SELECT name FROM products ORDER BY ?")) {
ps.setString(1, "price");
print(ps.executeQuery());
} catch (SQLException e) { System.out.println(" ORDER BY ?: " + e.getSQLState()); }
try {
conn.prepareStatement("SELECT name FROM ? ");
} catch (SQLException e) { System.out.println(" table name as parameter: " + e.getSQLState()); }
System.out.println("--- parameter metadata ---");
try (PreparedStatement ps = conn.prepareStatement("UPDATE products SET price = ? WHERE id = ?")) {
ParameterMetaData pm = ps.getParameterMetaData();
for (int i = 1; i <= pm.getParameterCount(); i++)
System.out.println(" parameter " + i + ": " + pm.getParameterTypeName(i));
}
}
}
static void print(ResultSet rs) throws SQLException {
var row = new ArrayList<String>();
try (rs) { while (rs.next()) row.add(rs.getString(1) + (rs.getMetaData().getColumnCount() > 1 ? " " + rs.getString(2) : "")); }
System.out.println(" " + row);
}
}
Output with H2 2.3:
--- string concatenation ---
SELECT name FROM users WHERE name = 'nobody' OR 1=1 --' AND password_hash = 'wrong'
logged in as ada
logged in as bob
SELECT name FROM users WHERE name = 'ada' --' AND password_hash = 'wrong'
logged in as ada
--- prepared statement ---
nobody' OR 1=1 -- -> no match
ada' -- -> no match
ada -> logged in as ada
--- reuse: parameters stay bound ---
[Pine stool 35.00, Oak shelf 89.90]
[Pine stool 35.00]
after clearParameters: 90012
--- dates, NULL and setObject ---
inserted 1
[Pine stool, Desk lamp, Gift card]
[0]
[1]
--- IN lists ---
[Hammer, Desk lamp]
[Hammer, Desk lamp]
--- LIKE with user input ---
unescaped: [Hammer, Oak shelf, Pine stool, 100% wool rug, Desk lamp, Gift card]
escaped: [100% wool rug]
--- what can't be a parameter ---
ORDER BY ?: 22018
table name as parameter: 42001
--- parameter metadata ---
parameter 1: DECIMAL
parameter 2: INTEGER
The program
The runnable demo needs no database because it looks at the SQL text itself. It shows how concatenated input changes the statement, while with placeholders the text stays the same and only the parameter list changes. A small Query builder assembles a product search from optional filters, an escaped LIKE pattern, a generated IN list and a whitelisted sort key, and it rejects an injection attempt through the sort key. Its prepare method shows how the collected values would be bound. Finally, the program calls the enquote helpers. They are default methods of Statement, so a dynamic proxy that forwards to them with InvocationHandler.invokeDefault (Java 16) can run them without a driver.
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.sql.*;
import java.util.*;
public class Solution {
// A builder that keeps SQL text and parameter values apart: the text only ever contains "?"
static class Query {
private final StringBuilder sql = new StringBuilder();
private final List<Object> params = new ArrayList<>();
Query sql(String fragment) { sql.append(fragment); return this; }
Query param(Object value) { sql.append('?'); params.add(value); return this; }
Query in(Collection<?> values) {
if (values.isEmpty()) throw new IllegalArgumentException("IN () is not valid SQL");
sql.append('(').append(String.join(", ", Collections.nCopies(values.size(), "?"))).append(')');
params.addAll(values);
return this;
}
@Override public String toString() { return sql + " params=" + params; }
// with a real connection: bind the parameters in order
PreparedStatement prepare(Connection conn) throws SQLException {
PreparedStatement ps = conn.prepareStatement(sql.toString());
for (int i = 0; i < params.size(); i++) ps.setObject(i + 1, params.get(i));
return ps;
}
}
static final Map<String, String> SORT_COLUMNS = Map.of("name", "p.name", "price", "p.price", "newest", "p.added DESC");
static Query productSearch(String nameLike, String supplier, BigDecimal maxPrice, List<String> countries, String sort) {
var q = new Query().sql("SELECT p.name, p.price FROM products p JOIN suppliers s ON s.supplier_id = p.supplier_id WHERE 1 = 1");
if (nameLike != null) q.sql(" AND p.name LIKE ").param("%" + escapeLike(nameLike) + "%").sql(" ESCAPE '!'");
if (supplier != null) q.sql(" AND p.supplier_id = ").param(supplier);
if (maxPrice != null) q.sql(" AND p.price <= ").param(maxPrice);
if (!countries.isEmpty()) q.sql(" AND s.country IN ").in(countries);
String orderBy = SORT_COLUMNS.get(sort); // identifiers can't be parameters: whitelist
if (orderBy == null) throw new IllegalArgumentException("unknown sort key: " + sort);
return q.sql(" ORDER BY " + orderBy);
}
static String escapeLike(String s) {
return s.replace("!", "!!").replace("%", "!%").replace("_", "!_");
}
public static void main(String[] args) throws SQLException {
System.out.println("--- concatenation lets input change the statement ---");
for (String input : List.of("ada", "nobody' OR 1=1 --", "x'; DROP TABLE users; --")) {
String sql = "SELECT * FROM users WHERE name = '" + input + "' AND password_hash = ?";
System.out.println(sql);
}
System.out.println("--- with a placeholder the SQL text never changes ---");
for (String input : List.of("ada", "nobody' OR 1=1 --")) {
var q = new Query().sql("SELECT * FROM users WHERE name = ").param(input).sql(" AND password_hash = ").param("h");
System.out.println(q);
}
System.out.println("--- building a dynamic search safely ---");
System.out.println(productSearch(null, null, null, List.of(), "name"));
System.out.println(productSearch("50%_off", "NORD", new BigDecimal("100"), List.of("Sweden", "Spain"), "newest"));
try {
productSearch(null, null, null, List.of(), "price; DROP TABLE products");
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
System.out.println("--- quoting helpers of java.sql.Statement (JDBC 4.3) ---");
// These are default methods, so any Statement has them. A proxy lets us call them without a database.
InvocationHandler handler = (proxy, method, methodArgs) -> {
if (method.isDefault()) return InvocationHandler.invokeDefault(proxy, method, methodArgs);
throw new SQLFeatureNotSupportedException(method.getName());
};
Statement stat = (Statement) Proxy.newProxyInstance(Statement.class.getClassLoader(), new Class<?>[] { Statement.class }, handler);
for (String s : List.of("Hammer", "Children's chair", "x' OR '1'='1"))
System.out.println("enquoteLiteral(" + s + ") = " + stat.enquoteLiteral(s));
for (String id : List.of("products", "Order", "first name", "x\"y"))
System.out.printf("enquoteIdentifier(%s, false) = %s, isSimpleIdentifier = %b%n",
id, quoteOrError(stat, id), stat.isSimpleIdentifier(id));
System.out.println("enquoteIdentifier(Order, true) = " + stat.enquoteIdentifier("Order", true));
System.out.println("enquoteNCharLiteral(Grüße) = " + stat.enquoteNCharLiteral("Grüße"));
}
static String quoteOrError(Statement stat, String id) {
try { return stat.enquoteIdentifier(id, false); }
catch (SQLException e) { return "SQLException: " + e.getMessage(); }
}
}
--- concatenation lets input change the statement ---
SELECT * FROM users WHERE name = 'ada' AND password_hash = ?
SELECT * FROM users WHERE name = 'nobody' OR 1=1 --' AND password_hash = ?
SELECT * FROM users WHERE name = 'x'; DROP TABLE users; --' AND password_hash = ?
--- with a placeholder the SQL text never changes ---
SELECT * FROM users WHERE name = ? AND password_hash = ? params=[ada, h]
SELECT * FROM users WHERE name = ? AND password_hash = ? params=[nobody' OR 1=1 --, h]
--- building a dynamic search safely ---
SELECT p.name, p.price FROM products p JOIN suppliers s ON s.supplier_id = p.supplier_id WHERE 1 = 1 ORDER BY p.name params=[]
SELECT p.name, p.price FROM products p JOIN suppliers s ON s.supplier_id = p.supplier_id WHERE 1 = 1 AND p.name LIKE ? ESCAPE '!' AND p.supplier_id = ? AND p.price <= ? AND s.country IN (?, ?) ORDER BY p.added DESC params=[%50!%!_off%, NORD, 100, Sweden, Spain]
rejected: unknown sort key: price; DROP TABLE products
--- quoting helpers of java.sql.Statement (JDBC 4.3) ---
enquoteLiteral(Hammer) = 'Hammer'
enquoteLiteral(Children's chair) = 'Children''s chair'
enquoteLiteral(x' OR '1'='1) = 'x'' OR ''1''=''1'
enquoteIdentifier(products, false) = products, isSimpleIdentifier = true
enquoteIdentifier(Order, false) = Order, isSimpleIdentifier = true
enquoteIdentifier(first name, false) = "first name", isSimpleIdentifier = false
enquoteIdentifier(x"y, false) = SQLException: Invalid name, isSimpleIdentifier = false
enquoteIdentifier(Order, true) = "Order"
enquoteNCharLiteral(Grüße) = N'Grüße'
Notice that the default isSimpleIdentifier accepts Order, although ORDER is a reserved word. Only a driver that overrides the method knows its database's keywords. Pass alwaysQuote = true when in doubt. Quoted identifiers are case-sensitive, though, so "Order" and ORDER name different tables.
Common questions
Do prepared statements protect against every kind of injection?
They protect values. They don't protect SQL fragments you assemble yourself: table or column names, sort directions, or whole WHERE clauses passed in from outside. Whitelist those, as the demo's Query builder does. Stored procedures that build dynamic SQL internally from their arguments can also be vulnerable.
How do I use LIKE with a parameter?
Put the wildcards in the value, not in the SQL: WHERE name LIKE ? with ps.setString(1, "%" + escaped + "%"). Escape %, _ and the escape character in user input, and declare it: LIKE ? ESCAPE '!'. Avoid \ as the escape character: MySQL treats it specially in string literals, and in Java source it has to be doubled.
How do I pass a list for IN (...)?
Generate one ? per element (String.join(",", Collections.nCopies(n, "?"))) and bind each value. With PostgreSQL and H2, = ANY(?) with conn.createArrayOf("INTEGER", values) uses a single parameter. Very long lists are better put into a temporary table and joined.
Which setter should I use for dates and times?
setObject(i, localDate), setObject(i, localDateTime) or setObject(i, offsetDateTime), with the java.time types (JDBC 4.2). Avoid java.sql.Date, Time and Timestamp in new code; they carry time-zone surprises. Read with rs.getObject(col, LocalDate.class).
Is it OK to keep a PreparedStatement open for the whole application?
No. It belongs to one connection, which a pool hands out to different threads over time. Prepare it where you use it, inside the try-with-resources that also holds the connection, and let the driver or pool cache it.
API reference
| API | Purpose |
|---|---|
Connection.prepareStatement(sql) | create a statement with ? parameters |
PreparedStatement.setInt, setString, setBigDecimal, setBoolean, setBytes, ... | bind a parameter by position, starting at 1 |
setObject(index, value), setObject(index, value, sqlType) | bind any value, including java.time types |
setNull(index, sqlType) | bind SQL NULL |
setArray(index, conn.createArrayOf(type, values)) | bind an array, for example for = ANY(?) |
executeQuery(), executeUpdate(), execute() | run with the current parameters |
clearParameters() | unset all parameters |
getParameterMetaData() | parameter count and types |
Statement.enquoteLiteral, enquoteIdentifier, isSimpleIdentifier, enquoteNCharLiteral | quoting helpers (JDBC 4.3) |
Summary
- Use
PreparedStatementwith?placeholders for every statement that contains variable values, and bind the values with setters numbered from 1. - Concatenating input into SQL allows SQL injection, where input changes the statement's structure. Parameters keep values as values.
- Parameters can't replace identifiers or keywords. Whitelist sort columns and table names, generate placeholders for IN lists, and escape
%and_in LIKE input. - Bound parameters persist across executions,
setNullpasses NULL, andsetObjecthandlesjava.timevalues. - Prepared statements let databases reuse execution plans, and drivers and pools cache them per connection.
Practice Questions
A search form passes the text "O'Brien" into "... WHERE last_name = '" + input + "'". What happens, and what would an attacker do with the same code?
The quote in O'Brien ends the string literal early, so the statement is a syntax error and the search for a legitimate name fails. An attacker can use the same flaw on purpose, with input like x' OR 1=1 -- or x'; DELETE FROM customers; --, to change what the statement does. A prepared statement with last_name = ? fixes both the bug and the vulnerability.
The user can sort a product list by name, price or date. Why doesn't ORDER BY ? work, and what should you do instead?
A parameter can only supply a value, and ORDER BY 'price' sorts by a constant string (or is rejected), not by the column. Map the user's choice to SQL text you control: Map.of("name", "name", "price", "price", "date", "added DESC").get(choice). Reject unknown keys, and concatenate only the mapped value.
How do you query for products whose IDs are in a List\<Integer\> of varying size with a prepared statement?
Generate one placeholder per element, "... WHERE id IN (" + String.join(", ", Collections.nCopies(ids.size(), "?")) + ")", then bind each ID with setInt(i + 1, ids.get(i)). Handle an empty list separately, since IN () is invalid. On PostgreSQL or H2, you can also use WHERE id = ANY(?) and bind one array with setArray.
Your prepared statement UPDATE products SET price = ? WHERE id = ? is executed in a loop. You set the price only once before the loop and the ID inside it. Is that correct?
Yes. Bound parameters keep their values until you set them again or call clearParameters(), so every execution uses the same price with a different ID. (For many rows, also consider a batch update, covered in article 65.)
A user searches product names for "50%_off". How do you bind the LIKE pattern so that it finds exactly that text anywhere in the name?
Escape the wildcards and declare the escape character: name LIKE ? ESCAPE '!', and bind "%" + input.replace("!", "!!").replace("%", "!%").replace("_", "!_") + "%". Without escaping, % and _ in the input would act as wildcards and match many unrelated names.
Previous: Executing SQL with JDBC: Statements, Result Sets and SQL Exceptions
Next: LOBs, SQL Escapes, Multiple Results and Generated Keys in JDBC
Related reading
- Executing SQL with JDBC: Statements, Result Sets and SQL Exceptions
- Connecting to a Database with JDBC: URLs, Drivers, DriverManager and DataSource
- JDBC Design and SQL Basics: How Java Talks to Databases
- Sending Email from Java: SMTP and Jakarta Mail
- A Simple HTTP Server in Java: jwebserver, HttpServer, Handlers and Filters

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.