Prepared Statements

The Fix: Parameters

Prepared statements (parameterised queries) send the SQL and the values separately. The database never treats the values as SQL, so injection is impossible.

// Node.js (mysql2)
const [rows] = await db.execute(
  'SELECT * FROM Users WHERE Email = ? AND PasswordHash = ?',
  [email, hash]
);

# Python (psycopg)
cur.execute("SELECT * FROM users WHERE email = %s", (email,))

// Java (JDBC)
PreparedStatement ps = conn.prepareStatement("SELECT * FROM Users WHERE Email = ?");
ps.setString(1, email);

More Defences

  • Use an ORM or query builder, which parameterise for you, and avoid their "raw SQL" escape hatches with string concatenation.
  • Table and column names cannot be parameters: validate them against an allow-list.
  • Never store plain passwords: store a slow hash (bcrypt, Argon2).
  • Return generic error messages; do not show database errors to users.
  • Give the application database account the least privileges it needs (next page).