How do I write SQL safely in Python and avoid injection?

When working with databases in Python, it's critical to write SQL queries safely to avoid SQL injection attacks. This can be done by using parameterized queries or prepared statements, which allow you to separate SQL logic from user input.

Here's an example using the SQLite3 library in Python:

import sqlite3 # Connect to the database connection = sqlite3.connect('example.db') cursor = connection.cursor() # Create a table cursor.execute('''CREATE TABLE users (username TEXT, password TEXT)''') # Safe insertion of user data username = "user_input_username" password = "user_input_password" cursor.execute('INSERT INTO users (username, password) VALUES (?, ?)', (username, password)) # Commit the changes and close the connection connection.commit() connection.close()

SQL injection parameterized queries SQLite3 Python database security prepared statements