← Back to all snippets
PYTHON

Prevent SQL Injection with Python's Psycopg2 Prepared Statements

Secure your PostgreSQL database queries in Python by using parameterized queries with the `psycopg2` library to effectively prevent SQL injection vulnerabilities.

import psycopg2
from psycopg2 import sql

def execute_secure_query(username_input):
    conn = None
    try:
        # Replace with your actual database connection details
        conn = psycopg2.connect(
            dbname="your_db_name",
            user="your_db_user",
            password="your_db_password",
            host="localhost"
        )
        cur = conn.cursor()

        # --- SECURE WAY: Using parameterized queries ---
        # The 'WHERE username = %s' is a placeholder. Psycopg2 handles escaping the value.
        query = sql.SQL("SELECT id, email FROM users WHERE username = %s")
        cur.execute(query, (username_input,)) # Pass parameters as a tuple/list

        user_data = cur.fetchone()
        if user_data:
            print(f"Found user: ID={user_data[0]}, Email={user_data[1]}")
        else:
            print(f"User '{username_input}' not found.")

        # --- INSECURE WAY (for comparison, DO NOT USE IN PRODUCTION) ---
        # This is vulnerable to SQL injection if username_input contains malicious code.
        # insecure_query = f"SELECT id, email FROM users WHERE username = '{username_input}'"
        # cur.execute(insecure_query)

    except psycopg2.Error as e:
        print(f"Database error: {e}")
    finally:
        if conn:
            conn.close()

# Example usage
print("--- Secure query with valid input ---")
execute_secure_query("john_doe")

print("
--- Secure query with potentially malicious input ---")
# This input would be catastrophic with string concatenation
execute_secure_query("admin' OR '1'='1")

print("
--- Secure query with SQL comment injection attempt ---")
execute_secure_query("test_user'; DROP TABLE users; --")
How it works: This Python snippet demonstrates how to prevent SQL injection when interacting with a PostgreSQL database using `psycopg2`. Instead of directly concatenating user input into SQL queries (which is highly vulnerable), it uses parameterized queries (prepared statements). The `sql.SQL` object and `%s` placeholder ensure that user-provided values are properly escaped and treated as literal data, not executable SQL code, thus neutralizing injection attempts.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs