PreparedStatement as Defense Against SQL Injection
Fast recall
Quick revision
Core answer
Whether you understand separation of query compilation from parameter binding.
Concatenating values into the SQL even while using a PreparedStatement.
Explain precompilation: structure is fixed, so values can't alter the query.
Interview-ready guide
Interview answer
A login query with username = ? AND password_hash = ? compares two values. The string ' OR '1'='1 remains a username value and cannot create a new predicate. The same protection applies to dates, numbers, and other bound types. Calling a concatenated query a PreparedStatement does not help: the unsafe fragment has already changed the structure before the driver sees it.
For example, owner = ? plus setString safely binds even an input containing quotes as one value. If the client chooses a sort column, I translate an allowlisted value to fixed SQL rather than concatenate arbitrary text.
PreparedStatement as Defense Against SQL Injection
Direct Answer
PreparedStatement protects bound values from being interpreted as SQL syntax. The SQL contains placeholders and the values are supplied through setters, so each value occupies a value position in the already defined statement structure. A driver may send or prepare that information in different ways; safety does not depend on separate packets or one universal server compilation sequence.
Common Mistakes & Pitfalls
- Concatenating values into the SQL even with a PreparedStatement — defeats it.
- Parameterizing identifiers:
?works for values, not table/column names. - Reusing one statement insecurely: still bind every value, don't inline any.
- Assuming it's only for SELECTs: parameterize INSERT/UPDATE/DELETE too.
Check your understanding
Answer these without looking back at the article.
- What is SQL injection and how does it work?
- What are other SQL injection prevention techniques besides PreparedStatement?
- Can SQL injection occur with JPA or Hibernate in Java?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.