Video in progress

How does SQL injection happen, and how does PreparedStatement protect against it?

If user input is concatenated directly into the SQL string, it becomes part of the SQL code and changes the query's logic. With PreparedStatement the query and the values are sent separately, so a value is never executed as code.

📖 Answer

The vulnerable code:

String sql = "SELECT * FROM users WHERE login = '" + login + "'";

If someone types ' OR '1'='1 into the login field, the query becomes WHERE login = '' OR '1'='1' and returns every user. Worse, they could send '; DROP TABLE users; --.

The right way:

String sql = "SELECT id, login FROM users WHERE login = ?";
try (PreparedStatement ps = con.prepareStatement(sql)) {
    ps.setString(1, login);   // as a value, not as code
    try (ResultSet rs = ps.executeQuery()) { ... }
}

JPA works the same way: the :login parameter is safe, but if you build the JPQL string with +, the problem comes back.

One gotcha: a parameter works only in place of a value. You can't pass a table name or an ORDER BY column with ?. If the user picks the sort column, check it against an allowed list (a whitelist): Set.of("created_at", "price").contains(sort).