Parameter Placeholders: Question Marks
What You'll Learn
You'll learn how to use question mark (?) placeholders to safely insert user-provided values into SQL queries without risking SQL injection attacks.
The Core Idea
Instead of building SQL queries by concatenating strings with variable values—which we now know is dangerous—we use placeholders that act like blank spaces in a form. The question mark (?) is the standard placeholder syntax for sqlite3 and many other DB-API compliant Python libraries.
Think of it like a Mad Libs game: you write a sentence with blanks ("My favorite color is ___"), and someone else fills in the values. The database library ensures those values are treated as data, never as executable SQL commands.
How Question Marks Work
When you write a parameterized query with sqlite3, you place a ? everywhere you want to insert a value:
import sqlite3
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
# Safe parameterized query using question marks
user_id = 42
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
Notice the second argument to execute(): a tuple of values (user_id,). The database driver automatically escapes and properly formats this value, preventing any malicious SQL from executing.
For multiple parameters, just add more question marks and values:
name = "Alice"
age = 30
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", (name, age))
The order matters: the first ? gets the first tuple value, the second ? gets the second, and so on.
Key Takeaway: Use question mark (?) placeholders with a tuple of values as the second argument to execute() to safely pass parameters in SQLite and other DB-API libraries—the database driver handles escaping automatically, preventing SQL injection.