Which of the following best explains why parameterized queries help prevent SQL injection attacks in Flask applications?
Think about how user input is handled inside the SQL command.
Parameterized queries keep the SQL code and user data separate. This means user input is treated only as data, not as part of the SQL command, preventing attackers from injecting harmful SQL.
Consider this Flask code snippet using raw string formatting for SQL:
user_id = "1 OR 1=1"
query = f"SELECT * FROM users WHERE id = {user_id}"
cursor.execute(query)
result = cursor.fetchall()What will result contain?
Look at how the user input changes the WHERE clause.
The input "1 OR 1=1" makes the WHERE clause always true, so all rows are returned. This shows why raw string formatting is dangerous.
Which of the following Flask code snippets correctly uses parameterized queries to safely select a user by id?
Check the parameter style and how parameters are passed as a tuple.
Option D uses the correct placeholder %s and passes parameters as a tuple. Option D is unsafe string formatting. Option D passes parameter correctly as a tuple but the placeholder ? is not used by all DB-API drivers in Flask (depends on the database). Option D uses named style but passes parameter incorrectly (should be a dict).
What error will this Flask code raise?
user_id = 5
cursor.execute("SELECT * FROM users WHERE id = ?", user_id)Look at how parameters are passed to execute.
The parameter must be passed as a tuple or list, even if it is a single value. Passing a single integer causes a TypeError.
Given this Flask code:
user_input = "1; DROP TABLE users;" query = "SELECT * FROM users WHERE id = " + user_input cursor.execute(query) rows = cursor.fetchall()
What will happen when this code runs?
Consider how the database driver handles multiple SQL statements in one execute.
Most database drivers do not allow multiple statements in one execute call, so this raises a syntax or operational error, preventing the DROP TABLE from running.