Let's write. Mastering SQLite3 in Python: A Complete Tutorial for Writing Fixed and Secure Queries
– the wildcard % is part of the parameter value:
# Commit all changes conn.commit()
You can copy and run this script directly.
# The ? placeholder handles quoting and escaping automatically cursor.execute('SELECT * FROM users WHERE name = ?', (search_name,)) sqlite3 tutorial query python fixed
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Alice",)) # Only one value, two placeholders
By default, SQLite returns rows as standard Python tuples, meaning you must access columns by their index (e.g., row[0] ). You can configure your connection to return dictionary-like row objects instead. Let's write
: Provide the actual values as a second argument—specifically in a # The "Fixed" and Secure way = sqlite3.connect( = conn.cursor() # Alex used a '?' placeholder cookie_name Oatmeal Raisin SELECT * FROM inventory WHERE name = ? # He passed the variable in a tuple (note the comma!) cursor.execute(query, (cookie_name,)) = cursor.fetchone() print(result) Use code with caution. Copied to clipboard Advanced Fixing: The "List" Problem
conn = sqlite3.connect(db_path)