Editor

Fix the SQL Injection Bug

Intermediate · Fix the bug · from Python SQLite: Build and Query Databases Without a Server

From the lesson: Python SQLite: Build and Query Databases Without a Server

Every app needs to store data somewhere. A to-do list needs to remember your tasks. A contacts app needs to save names and phone numbers. You could write everything to a text file, but what happens when you need to find all contacts in a specific city, or delete tasks older than a week?

Read the lesson

This code has a dangerous SQL injection vulnerability. Fix it by converting the string-formatted query to use parameterized queries with ? placeholders. The behavior should remain the same -- just make it safe.

import sqlite3
conn = sqlite3.connect(':memory:')
cursor = conn.cursor()
cursor.execute('CREATE TABLE users (name TEXT, role TEXT)')
cursor.executemany('INSERT INTO users VALUES (?, ?)', [
('Alice', 'admin'), ('Bob', 'user'), ('Charlie', 'user'),
])
conn.commit()
# BUG: SQL injection vulnerability!
search_role = 'admin'
cursor.execute(f"SELECT name FROM users WHERE role = '{search_role}'")
for row in cursor.fetchall():
print(row[0])

More SQLite exercises

All Python exercises · 50 practice problems · Standard Library Essentials quiz