Parameterize SQL queries in Python to prevent SQL injection
Safely fetch users from a SQLite database using parameterized queries to prevent SQL injection attacks.
Python code
26 linesimport sqlite3
def get_users_by_name(name):
"""Fetch users safely using parameterized query."""
conn = sqlite3.connect(':memory:')
cursor = conn.cursor()
# Create sample table and data
cursor.execute('CREATE TABLE users (id INTEGER, name TEXT)')
cursor.executemany('INSERT INTO users (name) VALUES (?)',
[('Alice',), ('Bob',), ('Carol',)])
# SAFE: Parameterized query prevents SQL injection
cursor.execute('SELECT * FROM users WHERE name = ?', (name,))
result = cursor.fetchall()
conn.close()
return result
if __name__ == "__main__":
# Test with normal input
print("Normal input:", get_users_by_name("Alice"))
# Test with injection attempt - safely returns empty, no injection
injection_attempt = "'; DROP TABLE users; --"
print("Injection attempt:", get_users_by_name(injection_attempt))
Output
Normal input: [(1, 'Alice')]
Injection attempt: []
How it works
The cursor.execute method accepts a SQL string with ? placeholders and a tuple of parameters. SQLite binds these values safely, escaping any dangerous characters. This ensures that user input is treated as data, not executable SQL. The injection attempt with '; DROP TABLE users; -- is passed as a literal string, so the query matches no rows and returns an empty list. Parameterized queries are the standard defense against SQL injection in Python.
Common mistakes
- Using string formatting or concatenation like f"SELECT * FROM users WHERE name = '{name}'" which is vulnerable.
- Forgetting to pass parameters as a tuple, e.g., passing a single string instead of (name,).
- Assuming parameterization only matters for web apps — databases used in scripts are also at risk.
Variations
- Use `?` with `sqlite3` or `%s` with `psycopg2` for PostgreSQL.
- Use an ORM like SQLAlchemy which always parameterizes queries under the hood.
Real-world use cases
- Handling user login forms that query a users table by username.
- Building search endpoints that match records based on user-supplied filter values.
- Logging database queries in a secure admin dashboard where input is untrusted.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.