Lesson · JDBC
SQL Injection: why parameterization ends it and escaping does not
15 min readSQL Injection & Security
Concatenate input into a query and you hand the attacker a parser: your data becomes their syntax, and a payload like ' OR '1'='1' -- logs in without a password. PreparedStatement fixes it at the protocol level, because the statement is parsed and planned before any value arrives. Identifiers are the one thing parameters cannot bind, and they need an allowlist instead.
Input becomes syntax
A SQL statement is a program, and the database parses it before running it. Build that statement with string concatenation and user input writes part of the program: by the time the parser sees the text, there is no difference between your code and their data. The classic login does exactly this.
Feed the username field O'Reilly and the query breaks rather than bypasses: the apostrophe closes the string literal early and the rest dangles as invalid syntax. Feed it ' OR '1'='1' -- and the structure changes: the quote closes the literal, OR '1'='1' is always true, and -- comments out the password check, so every row in the table matches.
String sql = "SELECT * FROM users WHERE username = '" + username + "' AND password_hash = '" + passwordHash + "'"; try (Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(sql)) { // username and hash are now program text if (rs.next()) { loginSucceeded = true; } }
- `O'Reilly`: an unbalanced quote, so the statement fails to parse. A broken login, not a bypass.
- `' OR '1'='1' --`: rewrites the WHERE predicate to always true and comments out the rest, so the first row is logged in without a password.
- `'; DROP TABLE users --`: a stacked statement. Whether it executes depends on driver and server multi-statement support, which is a configuration detail, not a control you can rely on.
The vulnerability is the concatenation, not the quote character. Once input is part of the string, the parser cannot tell your syntax from the attacker's.
Escaping is a per-dialect guess
The first instinct after seeing a bypass is to escape the dangerous characters: double the quotes, strip --, and the query survives. That instinct fails as a general strategy, because escaping is a string transformation that has to be correct for every dialect, encoding and data type, and it demonstrably is not.
- Encoding mismatches: escaping is defined in terms of the character set in play, so when client and server disagree, the bytes you escaped are not the bytes the parser reads.
- Numbers are not quoted:
WHERE id =plus input has no quote to escape, and quote-focused escaping protects nothing there. - LIKE has its own syntax:
%and_are wildcards inside a pattern, and escaping them is a different problem with different rules. - Second-order injection: a value stored cleanly in one request is concatenated into a statement later, at a point where the original escaping no longer applies.
- Driver and server settings differ: backslash escapes, multi-statement support and comment rules are per-dialect, per-version behaviour.
- Determinism: even when a hand-rolled escaper works today, it is a transformation you own and maintain; parameterization is a guarantee the protocol provides.
Escaping is a transformation you audit for each dialect; parameterization keeps the data out of the program text. One is a guess with a track record, the other is a boundary.
Parse first, bind after
PreparedStatement splits a statement into two things that travel separately: the SQL text, sent first and parsed by the server, and the parameter values, sent after and substituted into slots that already exist. The statement below is one fixed program; each ? is a hole for a value, not a position in a string.
The payload from the opening section becomes a parameter value, a piece of text compared against the username column. No user is literally called ' OR '1'='1' --, so the result set is empty, and the fact that the value contains quotes and an OR changes nothing.
The same boundary exists in every data layer: setString, setInt, setObject in JDBC, setParameter in JPA and JPQL. When a data access module skips it, that is the finding.
String sql = "SELECT 1 FROM users WHERE username = ? AND password_hash = ?"; try (PreparedStatement st = conn.prepareStatement(sql)) { // parsed and planned first st.setString(1, username); // then values arrive, as values st.setString(2, passwordHash); try (ResultSet rs = st.executeQuery()) { return rs.next(); } }
The parse tree is decided before your data arrives, so a parameter cannot change it. That sentence is the whole fix.
SQL injection one payload, three protocols
statement on the wire
SELECT * FROM users WHERE username = '<input>' AND password_hash = '<input>'
Act 1: a login handler builds its SQL by concatenation. Both fields are pasted into the statement text before anything parses it.
What cannot be parameterized
Parameters bind values, and not everything in a statement is a value. A ? cannot stand where the grammar requires an identifier (a table or column name) or a keyword (ASC, DESC). ORDER BY ? binds a value where a column name is expected: at best the ordering collapses to a constant, at worst the statement fails, depending on the database. Either way the column you meant never reaches the parser.
For user-chosen syntax, the safe pattern is an allowlist: the user picks from options you defined, and your code maps the pick to a fixed string. Unknown input falls back to a default, so the user never writes SQL, they choose among your constants.
private static final Map<String, String> SORTABLE = Map.of( "newest", "created_at", "name", "name", "price", "unit_price"); String column = SORTABLE.getOrDefault(requested, "created_at"); // unknown input goes to the default String sql = "SELECT id, name, unit_price FROM products ORDER BY " + column; // a constant, not user text
Values come from users and travel as parameters; syntax comes from your code and travels as constants. Anything that mixes the two is an injection you have not met yet.
Defence in depth around the one line
Parameterization closes the hole; the layers below shrink the blast radius of the next mistake. None of them is a substitute for the fix, and all of them are cheap.
- Least-privilege accounts: the application account holds DML on its own schema, no DDL and no reach into other schemas, so an injected statement can do far less.
- Separate accounts per service: two services that share a superuser account share every privilege either of them needs.
- Generic error messages: return a correlation id and log the detail server-side; a raw driver exception hands over table and column names for free.
- Never log full statements with credentials or personal data: parameters are exactly where tokens, emails and card numbers live.
- Keep drivers current: parameterization is carried out by the driver, and old drivers have old bugs.
- Treat a WAF as a speed bump: it blocks known payload shapes and misses mutated ones, because it cannot see your parse boundary.
Layers reduce blast radius, parameterization removes the hole. Keep both, and never let the layers convince you the hole is gone.
Frameworks do not absolve you
JPA and Hibernate do not give you a pass. createQuery with a concatenated JPQL string is the same concatenation in a different query language: the provider parses the string, and the payload lands in the parse just the same. ORMs that assemble dynamic filters from strings reintroduce the hole one layer up.
The fix stays the same wherever the query is written: bind the values, so they travel beside the query text. In JPA that is setParameter or the Criteria API's typed predicates; in native queries it is the same ? and named parameters JDBC already gave you.
// Wrong: the name is concatenated into JPQL, which is still parsed as a query language. em.createQuery("FROM User u WHERE u.name = '" + name + "'"); // Right: a named parameter, bound as a value exactly like a JDBC parameter. em.createQuery("FROM User u WHERE u.name = :name", User.class) .setParameter("name", name) .getResultList();
The injection surface is wherever strings become queries: JDBC, JPQL, HQL, native SQL or a dynamic filter builder. Binding parameters is your job in all of them.
Half parameterized is still injectable
A prepared statement with one concatenated column is not mostly safe. `ORDER BY ` plus raw input passes every value check, because the hole is structural: identifiers and keywords sit outside what parameters can bind. The same applies to table names, sort direction and dynamically assembled WHERE fragments. Bind the values, allowlist the syntax.
Interview angles
How does SQL injection actually work?+
String concatenation puts attacker input into the statement text before the server parses it, so the input can add operators, comments or whole statements. ' OR '1'='1' -- is the shortest demonstration: an always-true predicate with the password check commented out.
The database is not misbehaving. It parses the only text it received, and that text happens to contain an OR that your code did not write.
Why does parameterization stop it when escaping does not?+
The statement text is parsed and planned before parameter values arrive, and a value can only fill a slot that already exists. Escaping transforms text and must be right for every dialect, encoding and data type; parameterization is a protocol-level guarantee.
Common misconception: That a prepared statement is mainly a performance feature. Plan reuse is a bonus; the guarantee is structural, and it holds even when nothing is reused.
Can you parameterize a table name or an ORDER BY column?+
No: parameters bind values. Map the user's choice to a fixed identifier from an allowlist and reject everything not in the set, with a safe default for unknown input.
It binds a string constant where the parser expects an identifier: the ordering is meaningless at best and the statement can fail outright, depending on the database. Either way the column name you meant never reaches the parser.
Follow-up: What does ORDER BY ? actually do, then?
An ORM generates the SQL. Are you still exposed?+
Yes, wherever a string is built: concatenated JPQL, HQL and native queries inject exactly like JDBC, and dynamic query builders that assemble fragments are a known leak. Use setParameter or typed criteria and treat string-built query code as the finding it is.
What limits the damage when something still gets through?+
Least-privilege database accounts (DML on the application schema only, no DDL, no cross-schema reach), separate accounts per service, generic error messages, and no full statements in logs where parameters carry tokens or personal data.