Parameterized Statements

Parameterized statements (also called prepared statements) separate SQL commands from parameter values, preventing injection attacks.

SQL injection happens when an application builds a query by pasting user input into a string:

cursor.execute("SELECT * FROM users WHERE email = '" + email + "'")

If email contains a quote character, the attacker can close the string early and add SQL of their own. A parameterized statement uses a placeholder instead, and passes the value alongside the query:

cursor.execute("SELECT * FROM users WHERE email = %s", (email,))

The database driver sends the query and the value separately (or escapes the value correctly), so the database treats the value as data, however many quotes it contains. Every mainstream language and database supports parameterized statements, and most ORMs use them under the hood. Use them for every query that includes input from outside your code.

Placeholders can only stand in for values, not for table or column names. If a user chooses which column to sort by, check their choice against an allow list of column names.

Further Reading

Learn it hands-on

If you are vulnerable to SQL Injection, attackers can run arbitrary commands against your database.