SQL injection
SQL injection is when untrusted text becomes part of a SQL command. The database then runs the attacker's SQL. Bind parameters. Do not concatenate user strings into queries.
Detailed Explanation
select * from users where name = '" + name + "'" with name equal to ' OR '1'='1 returns every user. Worse payloads run drop table or steal other rows. The bug is treating data as code.
The fix is a prepared statement: where name = ? and setString(1, name). The driver sends the value out of band. It cannot close the quote. JPA named parameters (:name) and Spring NamedParameterJdbcTemplate do the same. Query builders that still concat ("order by " + col) remain dangerous: whitelist column names.
Injection also happens in like patterns (% and _), in identifiers (table names you cannot bind), and in native queries you build with StringBuilder. Hibernate does not make concatenation safe. Stored procedures that concat inside PL/pgSQL have the same hole.
You reach for this page whenever you write SQL or JPQL that includes request data. You review every + next to a query string. You do not "escape quotes" by hand; you will miss a dialect.
The cost of a successful injection is a data breach. The cost of a whitelist for sort columns is a small map (name → u.name). The cost of dynamic SQL you truly need is an allow-list plus tests that try quotes and comments.
Error messages that print SQL and values help attackers. Log them privately. Least privilege on the DB user limits the blast of a missed bind.
ORMs do not cancel this rule. A native query built with + request.getParameter("sort") is the same hole. So is a JPA Criteria API path that still interpolates a string you did not whitelist. Treat every query as hostile input plus a template. If you cannot point at the placeholder, you are not done. Security reviews look for createNativeQuery, createQuery, and Statement.execute next to string addition. Make those searches boring.
Code Examples
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Safe {
static boolean exists(Connection c, String name) throws Exception {
try (PreparedStatement ps = c.prepareStatement(
"select 1 from users where name = ?")) {
ps.setString(1, name); // data, not SQL
try (ResultSet rs = ps.executeQuery()) {
return rs.next();
}
}
}
}public class Unsafe {
static String broken(String name) {
// Never do this. Shown as the anti-pattern.
return "select 1 from users where name = '" + name + "'";
}
public static void main(String[] args) {
System.out.println(broken("Ada").contains("Ada")); // prints: true
}
}Common Gotchas
Concatenating request parameters into SQL is an injection
bind or whitelist.
JPQL concat is still injection
`createQuery("... " + userInput)` is unsafe.
You cannot bind identifiers
allow-list sort/filter column names.