Skip to lesson

PreparedStatement and ? placeholders

Escaping quotes by hand never ends: one forgotten query lets an attacker in. A safer plan is to send the SQL and the typed values separately, so a value can never act as a command.

prepareStatement and ? placeholders

A PreparedStatement is a SQL query with ? placeholders where the values go. You fill each ? with a set method, and the driver keeps the values apart from the SQL, so input never becomes part of the command.

connection.prepareStatement(sql) takes SQL with a ? in every spot a value belongs. Example 1 looks up a product by SKU with one placeholder, then tries a SKU that does not exist.

Example 1 · A prepared SELECT with one placeholder

Runs in: a Maven project with the MySQL driver and the ShopLite database

FindBySku.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;
public class FindBySku {    static void findBySku(Connection con, String sku) throws SQLException {        String sql = "SELECT name, price FROM products WHERE sku = ?";        try (PreparedStatement ps = con.prepareStatement(sql)) {            ps.setString(1, sku);            try (ResultSet rs = ps.executeQuery()) {                if (rs.next()) {                    System.out.println(sku + " -> " + rs.getString("name") + " Rs " + rs.getBigDecimal("price"));                } else {                    System.out.println(sku + " -> not found");                }            }        }    }
    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) {            findBySku(con, "MOB-RN13");            findBySku(con, "NO-SUCH");        }    }}
Output
MOB-RN13 -> Redmi Note 13 5G Rs 17999.00
NO-SUCH -> not found

What this code does

  • The SQL holds one ?. ps.setString(1, sku) fills it, then executeQuery returns the rows.
  • Both the PreparedStatement and the ResultSet are in try-with-resources, so both close on their own.

The ? is not a quote and not a column: WHERE sku = ? means "one value goes here". Every value supplied later is pure data, so a quote or a word like OR inside it stays part of the value.

With Connector/J's default settings the driver builds the final SQL itself and writes each value in as a safely escaped literal. With useServerPrepStmts=true the server plans the ? version and receives the values separately.

Order of execution

Order the steps of a prepared query

Arrange the steps that read one product by SKU.

setString and the 1-based index

A ? placeholder marks the spot of one value in a SQL string. Placeholders are numbered from 1, left to right, and each is filled with one set method before the statement runs.

You fill placeholders with setString, setInt, setBigDecimal and similar. The first argument is the number of the ?, counting from 1 (not 0), left to right.

Java
String sql = "UPDATE products SET price = ? WHERE sku = ?";PreparedStatement ps = con.prepareStatement(sql);ps.setBigDecimal(1, newPrice);   // first ?ps.setString(2, sku);            // second ?ps.executeUpdate();
The SQL UPDATE products SET price = ? WHERE sku = ? has two placeholders. The first ? is number 1 and is filled by setBigDecimal(1, price). The second ? is number 2 and is filled by setString(2, sku). Numbers start at 1 and run left to right.

For UPDATE products SET price = ? WHERE sku = ?, setBigDecimal(1, price) fills the first ? and setString(2, sku) the second. Then executeQuery() (for a SELECT) or executeUpdate() (for a change) runs it.

The login attack now fails

Run the same login with a PreparedStatement, and the attacker's ' OR '1'='1 or admin' -- is only a value. Example 2 sends both attacks and both are rejected.

Two ways to send the text ' OR '1'='1 as a password. Joined with plus, it becomes part of the SQL, so every row matches. With a ? placeholder, the SQL keeps its shape (password = ?) and the text travels apart as a value, so no user matches.

Example 2 · The login attack fails now

Runs in: a Maven project with the MySQL driver and a practice app_user table

SafeLogin.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;
public class SafeLogin {    static String login(Connection con, String username, String password) throws SQLException {        String sql = "SELECT user_id, role FROM app_user WHERE username = ? AND password = ?";        try (PreparedStatement ps = con.prepareStatement(sql)) {            ps.setString(1, username);            ps.setString(2, password);            try (ResultSet rs = ps.executeQuery()) {                if (rs.next()) return "OK  user_id=" + rs.getInt(1) + " role=" + rs.getString(2);                return "rejected";            }        }    }
    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) {            System.out.println("Real login:   " + login(con, "asha", "asha@123"));            System.out.println("OR attack:    " + login(con, "x' OR '1'='1", "x' OR '1'='1"));            System.out.println("Comment hack: " + login(con, "admin' -- ", "anything"));        }    }}
Output
Real login:   OK  user_id=1 role=USER
OR attack:    rejected
Comment hack: rejected

What this code does

  • The real login still works. The two attacks that broke the string-built login are now rejected.
  • The database searches for a password equal to the literal text x' OR '1'='1, and for a username equal to admin' -- . No such rows exist, so the input stays harmless data.

The database looks for a user whose password is literally the text ' OR '1'='1. No such user exists, so the login is rejected: the input never becomes part of the query.

Names cannot be parameters: use an allow-list

An allow-list is a fixed set of values the program accepts, such as the real column names it may sort by. Anything outside the set is rejected, so only names you wrote ever reach the SQL.

A ? can stand only for a value, never for a table or column name, so ORDER BY ? does not work. For a changing sort column, look the choice up in an allow-list. Example 3 does this.

Example 3 · A safe dynamic sort with an allow-list

Runs in: a Maven project with the MySQL driver and the ShopLite database

SafeSort.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.List;import java.util.Set;
public class SafeSort {    static final Set<String> ALLOWED = Set.of("name", "price");
    static void listMobiles(Connection con, String sortColumn) throws SQLException {        if (!ALLOWED.contains(sortColumn)) {            System.out.println("Refused unknown sort column: " + sortColumn);            return;        }        String sql = "SELECT name, price FROM products WHERE category_id = ? ORDER BY " + sortColumn;        try (PreparedStatement ps = con.prepareStatement(sql)) {            ps.setInt(1, 2);            try (ResultSet rs = ps.executeQuery()) {                System.out.println("Mobiles sorted by " + sortColumn + ":");                while (rs.next()) System.out.println("  " + rs.getString(1) + " - " + rs.getBigDecimal(2));            }        }    }
    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) {            for (String choice : List.of("price", "stock; DROP TABLE products")) {                listMobiles(con, choice);            }        }    }}
Output
Mobiles sorted by price:
  Redmi Note 13 5G - 17999.00
  Samsung Galaxy M35 - 19999.00
  iPhone 15 128GB - 69900.00
Refused unknown sort column: stock; DROP TABLE products

What this code does

  • The value in the WHERE is a bound parameter (?), but the sort column is joined into the SQL, so it must be checked.
  • price is in the allow-list, so the sort runs. The attack text is not in the list, so it is refused and never reaches the query.

With ORDER BY ? the driver wraps the name in quotes, so MySQL sorts by a constant text and not by the column.

Rule of thumb: values use ? and a set method; identifiers (table and column names) use an allow-list you control.

Two errors you will meet

Two mistakes cause most placeholder errors: a wrong parameter number, and running the statement before every ? has a value. Example 4 triggers both and prints the messages.

Example 4 · The two placeholder errors

Runs in: a Maven project with the MySQL driver and the ShopLite database

ParamErrors.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;
public class ParamErrors {    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) {
            String sql = "SELECT name FROM products WHERE sku = ?";
            try (PreparedStatement ps = con.prepareStatement(sql)) {                ps.setString(2, "MOB-RN13");   // there is no parameter 2                ps.executeQuery();            } catch (SQLException e) {                System.out.println("A: " + e.getMessage());            }
            try (PreparedStatement ps = con.prepareStatement(sql)) {                ps.executeQuery();             // parameter 1 was never set            } catch (SQLException e) {                System.out.println("B: " + e.getMessage());            }        }    }}
Output
A: Parameter index out of range (2 > number of parameters, which is 1).
B: No value specified for parameter 1

What this code does

  • The SQL has one ?, so setString(2, ...) asks for a placeholder that does not exist: Parameter index out of range.
  • Running the query without setting the one ? gives No value specified for parameter 1. Set every placeholder before running.

Parameter index out of range means you set a ? number that does not exist, such as setString(2, ...) when the SQL has one ?. Count the placeholders: indexes run 1, 2, 3 with none skipped.

No value specified for parameter N means the statement ran before placeholder N was filled. Set every ? before calling executeQuery or executeUpdate.

Fix the error

Fix the placeholder error

Read the error, then pick the line that fixes it.

Round 1 of 2

Pick the line that replaces line 3 so the query works.

String sql = "SELECT name FROM products WHERE sku = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(2, "MOB-RN13");
ResultSet rs = ps.executeQuery();

Error

java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1).

Next step

Check your understanding

10 quick questions