PYTHON

Prevent SQL Injection with Parameterized Queries

Learn to prevent SQL injection attacks in Python by using parameterized queries with the `sqlite3` module, ensuring secure database interactions for web applications.

import sqlite3

def create_user(username, email, password_hash):
    conn = None
    try:
        conn = sqlite3.connect('database.db')
        cursor = conn.cursor()
        
        # Use parameterized queries to prevent SQL injection
        sql = "INSERT INTO users (username, email, password_hash) VALUES (?, ?, ?)"
        cursor.execute(sql, (username, email, password_hash))
        conn.commit()
        print(f"User {username} created successfully.")
    except sqlite3.Error as e:
        print(f"Database error: {e}")
    finally:
        if conn:
            conn.close()

# Example usage (password_hash should ideally be generated using a strong hashing algorithm like bcrypt)
# create_user('john_doe', '[email protected]', 'secure_hash_123')
# create_user('jane_smith', '[email protected]', 'another_secure_hash')
How it works: This Python snippet demonstrates how to prevent SQL injection attacks using parameterized queries with the `sqlite3` module. Instead of directly embedding user input into the SQL string, placeholders (`?`) are used. The actual values are passed as a separate tuple to the `execute` method. This separation ensures that the database driver distinguishes between SQL code and user-provided data, preventing malicious input from altering the query's intent.

Need help integrating this into your project?

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

Hire DigitalCodeLabs