Why are parameterized queries preferred over string formatting?
cur.execute(f"SELECT * FROM users WHERE name = '{name}'") # A
cur.execute("SELECT * FROM users WHERE name = %s", (name,)) # BOptions
- A is faster, because it skips the handling of the parameters
- B prevents SQL injection, as values travel apart from the SQL text (Correct option)
- They are equivalent in safety and also in behavior
- B only works in SQLite and not in the other databases
Answer
B prevents SQL injection because values are sent separately from the SQL text
Why
In A, user input becomes part of the SQL code. If name is ' OR '1'='1, the query returns every user. That attack is SQL injection.
In B, the SQL and the value travel separately; the database always treats name as data, never as code.
Never build SQL with f-strings from user input.
Remember
Always pass values as parameters, never inside the SQL string.