PreparedStatement: Blocking SQL Injection

PreparedStatement: Blocking SQL Injection in Java: This is the single most important security topic in database programming.

Concept Explanation

This is the single most important security topic in database programming. Gluing user input into a SQL string lets an attacker rewrite your query.

Consider a login built by concatenation:

// NEVER DO THIS
String sql = "SELECT * FROM users WHERE name = '" + input + "'";

If the user types ' OR '1'='1, the query becomes:

SELECT * FROM users WHERE name = '' OR '1'='1'

'1'='1' is always true, so every row matches and the attacker logs in as anyone. Worse input ('; DROP TABLE users; --) can destroy data.


The Fix: Parameterised Queries

A PreparedStatement sends the query structure and the values to the database separately. Values can never be reinterpreted as SQL syntax.

String sql = "SELECT id, email FROM users WHERE name = ? AND active = ?";

try (PreparedStatement pst = conn.prepareStatement(sql)) {
    pst.setString(1, userInput);   // placeholders are 1-indexed
    pst.setBoolean(2, true);

    try (ResultSet rs = pst.executeQuery()) {
        while (rs.next()) {
            System.out.println(rs.getInt("id") + " -> " + rs.getString("email"));
        }
    }
}

Now ' OR '1'='1 is treated as a literal name to search for. It simply finds nothing.


Setter Methods

MethodJava type
setStringString
setInt, setLongwhole numbers
setDouble, setBigDecimaldecimals (use BigDecimal for money)
setBooleanboolean
setTimestampdates and times
setNullexplicit SQL NULL

The Performance Bonus

Databases cache the execution plan for a prepared query. Running the same statement in a loop with different values is measurably faster than sending a fresh string each time.


Common Mistakes

  1. Zero-indexed placeholders: setString(0, ...) throws. Parameters start at 1.
  2. Quoting the placeholder: Write name = ?, never name = '?' — the latter is a literal question mark.
  3. Parameterising identifiers: Table and column names cannot be placeholders. Validate those against an allow-list instead.
  4. Thinking an ORM makes you safe: Hibernate raw queries are just as injectable if you concatenate.

Best Practices

  • Treat concatenated SQL as a bug: If user data touches a query string, rewrite it.
  • Least privilege: The app's database user should not have DROP rights.
  • Never echo raw SQL errors to users — they reveal your schema.

Practice Exercises

  1. The Attack: Build a deliberately vulnerable concatenated query in a throwaway database and log in with ' OR '1'='1. Then fix it with a PreparedStatement and confirm the attack fails.
  2. The Batch Insert: Use one PreparedStatement in a loop with addBatch() and executeBatch() to insert 100 rows.
  3. The Allow-List: Write a method that accepts a column name to sort by, validating it against a fixed set before building the query.