Skip to lesson

Practice: prepared statements

Habits only stick when you practise them, and one forgotten + in one query is enough for an attack. These recaps make safe SQL automatic before you build the mini project.

Recap: never build SQL from input

A bound parameter is a value given to a ? placeholder with a set method. It is sent as data and can never change the SQL.

A query built with + lets input become SQL; the same query with ? keeps it a value. Example 1 runs both with the attacker username admin' -- .

Example 1 · Unsafe vs safe login side by side

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

ReviewUnsafeVsSafe.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class ReviewUnsafeVsSafe {    static String unsafeLogin(Connection con, String username, String password) throws SQLException {        String sql = "SELECT user_id FROM app_user WHERE username = '" + username                + "' AND password = '" + password + "'";        try (Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql)) {            return rs.next() ? "logged in as user_id " + rs.getInt(1) : "rejected";        }    }
    static String safeLogin(Connection con, String username, String password) throws SQLException {        String sql = "SELECT user_id 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()) {                return rs.next() ? "logged in as user_id " + rs.getInt(1) : "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"))) {            String badUser = "admin' -- ";            System.out.println("Unsafe, attacker input: " + unsafeLogin(con, badUser, "anything"));            System.out.println("Safe,   attacker input: " + safeLogin(con, badUser, "anything"));        }    }}
Output
Unsafe, attacker input: logged in as user_id 3
Safe,   attacker input: rejected

What this code does

  • The unsafe version lets admin' -- comment out the password check and logs the attacker in as user 3.
  • The safe version treats the same text as a username value, finds no such user, and rejects it. Same attack, two outcomes.

Recap: bind every value with the right type

Each value gets the set method that matches its column, and for LIKE the % goes into the bound value. Example 2 binds an id, a price range, a name pattern and a flag in one query.

Example 2 · Every value bound by type

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

ReviewBindings.javaJava
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;
public class ReviewBindings {    public static void main(String[] args) throws SQLException {        String sql = "SELECT name, price FROM products"                + " WHERE category_id = ? AND price BETWEEN ? AND ? AND name LIKE ? AND is_active = ?"                + " ORDER BY price";        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));             PreparedStatement ps = con.prepareStatement(sql)) {            ps.setInt(1, 4);            ps.setBigDecimal(2, new BigDecimal("500.00"));            ps.setBigDecimal(3, new BigDecimal("2500.00"));            ps.setString(4, "%r%");            ps.setBoolean(5, true);            try (ResultSet rs = ps.executeQuery()) {                while (rs.next()) System.out.println(rs.getString(1) + " Rs " + rs.getBigDecimal(2));            }        }    }}
Output
boAt Airdopes 141 Rs 1299.00
Mi Power Bank 20000mAh Rs 2199.00

What this code does

  • Five placeholders, five set calls: an int id, two BigDecimal bounds, a LIKE pattern and a boolean.
  • The % is inside the bound value "%r%", so the SQL stays name LIKE ? and the search is safe.

Recap: generated keys and batches

A generated key is the id MySQL creates for a new row with AUTO_INCREMENT. Ask for it with RETURN_GENERATED_KEYS and read it with getGeneratedKeys().

Read a new row's id with RETURN_GENERATED_KEYS, and insert many rows in one trip with a batch. Example 3 creates a category, reads its id and adds three products to it in one batch.

Example 3 · Generated key plus a batch

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

ReviewKeysAndBatch.javaJava
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.List;
public class ReviewKeysAndBatch {    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"))) {            con.setAutoCommit(false);            int catId;            try (PreparedStatement ps = con.prepareStatement(                    "INSERT INTO categories (name) VALUES (?)", Statement.RETURN_GENERATED_KEYS)) {                ps.setString(1, "Toys");                ps.executeUpdate();                try (ResultSet keys = ps.getGeneratedKeys()) {                    keys.next();                    catId = keys.getInt(1);                }            }            List<String> toys = List.of("Building Blocks", "Toy Car", "Puzzle 500");            try (PreparedStatement ps = con.prepareStatement(                    "INSERT INTO products (sku, name, category_id, price, stock) VALUES (?, ?, ?, ?, ?)")) {                int i = 1;                for (String name : toys) {                    ps.setString(1, "TOY-" + i);                    ps.setString(2, name);                    ps.setInt(3, catId);                    ps.setBigDecimal(4, new BigDecimal("499.00"));                    ps.setInt(5, 20);                    ps.addBatch();                    i++;                }                int added = ps.executeBatch().length;                System.out.println("Category id " + catId + " now has " + added + " products");            }            con.rollback();        }    }}
Sample output
Category id 8 now has 3 products

What this code does

  • The category INSERT uses RETURN_GENERATED_KEYS, so catId holds the new id, whatever the database assigns.
  • Each product uses that catId and is added with addBatch, then all three go in one executeBatch.

Reading code for injection holes

In a review, scan for one thing: user input joined into SQL with +. Any value glued into the text is a hole, whether the SQL is a SELECT, UPDATE, DELETE or a LIKE.

Two spots hide in plain sight. A sort column after ORDER BY cannot be a parameter, so it needs an allow-list. A numeric filter such as WHERE id = " + id has no quotes, so quote-escaping does nothing; it still needs a ?.

Find the bug

Find the injection hole

Select the line that is wrong.

Which line lets the typed city become SQL?

Round 1 of 3

Next step

Check your understanding

12 quick questions