Stop 13 · Databases, JDBC & JPATopics · 9/12

PreparedStatement & SQL Injection

Part of the Java Roadmap

In short

SQL injection has been near the top of web security risk lists for years, and it comes from one habit: gluing user input into SQL strings. PreparedStatement kills that habit in one line.

Building SQL by joining strings lets attackers inject their own SQL through user input. PreparedStatement sends the query and the values separately using ? placeholders, which blocks injection and lets the database reuse the plan.

The jaadu sits at a bank counter neatly writing into printed boxes on a paper form, while a sneaky crumpled note tries to slip in under the form and gets blocked by the clerk's hand.

Think of it like this

The bank form with boxes

A bank form has printed text and empty boxes. Whatever you write in the "Name" box is treated as a name, even if you write "and also transfer ₹1 lakh to me". The clerk never reads it as an instruction. PreparedStatement is that form: the SQL is printed, and user input only ever goes into the ? boxes.

Watch it happen

Same login, two ways

String concatenation

  • "... WHERE email = '" + email + "'"
  • Input ' OR '1'='1 changes the query
  • Attacker logs in as anyone

PreparedStatement

  • "... WHERE email = ?"
  • Value is sent separately from the SQL
  • Input is only ever data, never code

Never build SQL with user input. Use ? placeholders and setString, setInt and friends.

The big ideas

What you need to know

How injection works

If input becomes part of the SQL text, a quote character can end your string and start the attacker's own SQL.

? placeholders

Write the query once with ?, then bind values with setString(1, ...), setInt(2, ...). Indexes start at 1.

Also faster

The database can reuse the parsed query plan for repeated executions with different values.

Not for names

Placeholders work for values only. Table or column names (like a sort column) must come from a fixed allow-list.

See it in code

Walk through the code

java
1import java.sql.*;2import java.util.Optional;3 4public class UserDao {5    private final Connection conn;6 7    public UserDao(Connection conn) { this.conn = conn; }8 9    public Optional<String> findName(String email) throws SQLException {10        String sql = "SELECT name FROM users WHERE email = ?";11        try (PreparedStatement ps = conn.prepareStatement(sql)) {12            ps.setString(1, email);13            try (ResultSet rs = ps.executeQuery()) {14                return rs.next() ? Optional.of(rs.getString("name")) : Optional.empty();15            }16        }17    }18 19    public int addCredits(long userId, int credits) throws SQLException {20        String sql = "UPDATE users SET credits = credits + ? WHERE id = ?";21        try (PreparedStatement ps = conn.prepareStatement(sql)) {22            ps.setInt(1, credits);23            ps.setLong(2, userId);24            return ps.executeUpdate();25        }26    }27}

1/4The SQL has a ? where the value goes. It is fixed text, no concatenation.

Even if email is ' OR '1'='1, the database just looks for a user with that strange email address.

Save yourself the pain

Common mistakes

Oops

Escaping quotes yourself with replace("'", "''").

Do this instead

Hand-made escaping misses edge cases. Let PreparedStatement bind the value.

Oops

Using a placeholder for a column name: ORDER BY ?.

Do this instead

That binds a constant string, so nothing sorts. Check the column against an allow-list like Set.of("name", "city") and then add it.

Oops

Thinking an ORM makes you immune.

Do this instead

JPQL or native queries built by string concatenation are injectable too. Use named parameters like :email.

Your mission

Hack it, then fix it

~25 min

Quick check

Why does PreparedStatement prevent SQL injection?

Go deeper

  1. 1Write a login query by string concatenation and break it with ' OR '1'='1.
  2. 2Rewrite it with PreparedStatement and setString and confirm the attack fails.
  3. 3Use PreparedStatement for every query that includes user input from now on.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge