Parameterize SQL queries in Python to prevent SQL injection

Safely fetch users from a SQLite database using parameterized queries to prevent SQL injection attacks.

Easy Python 3.9+ Aug 9, 2026 Files & data 15 views 0 copies

Python code

26 lines
Python 3.9+
import 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

stdout
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

  1. Use `?` with `sqlite3` or `%s` with `psycopg2` for PostgreSQL.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.