Codectionary / Developer documentation / Python

SQLite Parameterized Queries

sqlite3 provides a local SQL database interface. Bound parameters separate data values from SQL syntax. This example uses an in-memory database and requires a Python build with sqlite3. Run as a Python 3.11+ script.

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])
  1. Expected output: 4
  2. 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

Specifications & further reading