1 / 8 · Book 15 · Your First SELECT -- Reading the Source of Truth · drill: interview Q&A⊞ allnext →Get the book →
1.11Parameterized Queries (Prevent SQL Injection)
Always use parameterized queries in test code:
# BAD: string interpolation -- SQL injection vulnerability
cursor.execute(f"SELECT * FROM users WHERE email = '{email}'")
# GOOD: parameterized query -- safe
cursor.execute("SELECT * FROM users WHERE email = %s", (email,))
# GOOD: named parameters
cursor.execute(
"SELECT * FROM users WHERE email = %(email)s AND role = %(role)s",
{"email": email, "role": "admin"}
)
Common Mistake: Even in test code, never use string interpolation for SQL queries. Test data can contain special characters like single quotes (
O'Brien) that will break your query. Parameterized queries handle this automatically. It is also a habit that prevents catastrophic mistakes when someone copies your pattern into production code.