Syntax
connection.execute("SELECT ... WHERE name = ?", (name,))Examples
SQLite Parameterized Queries
Run as a Python 3.11+ script.
import sqlite3
from contextlib import closing
with closing(sqlite3.connect(":memory:")) as db:
db.execute("CREATE TABLE stock (name TEXT, quantity INTEGER)")
db.execute("INSERT INTO stock VALUES (?, ?)", ("tea", 4))
db.commit()
row = db.execute("SELECT quantity FROM stock WHERE name = ?", ("tea",)).fetchone()
print(row[0])- Expected output: 4
- The single-element tuple supplies one parameter. closing closes the connection; a connection’s own context manager manages transactions but does not itself close it.
Best practices
- Bind values instead of interpolating user input into SQL.
- Commit intended changes and close connections explicitly.
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference