PYTHON SQLITE · LESSON 2 OF 4

Bind values safely

Use placeholders for values instead of building SQL from user input.

The question mark binds one value. A one-item tuple needs a trailing comma. Parameters cannot substitute table or column names; choose identifiers from a trusted allowlist. Try changing the search value to text containing a quote: it remains data.

Run it on your computer

python3 parameterized-queries.py

Requires Python 3.12+. The script creates its own in-memory sample. It does not read your browser database or upload anything.

import sqlite3

con = sqlite3.connect(":memory:", autocommit=False)
try:
    with con:
        con.execute("CREATE TABLE notes (body TEXT NOT NULL)")
        con.executemany("INSERT INTO notes VALUES (?)", [("Sam's note",), ("Another note",)])
    search = "Sam's note"
    rows = con.execute("SELECT body FROM notes WHERE body = ?", (search,)).fetchall()
    print(rows)
finally:
    con.close()

Expected output

[("Sam's note",)]

Try a change

Add a second WHERE condition using another placeholder. Keep values in the same order as their placeholders.

Practice SQL in the browser or use the Python sqlite3 documentation for API details.

Next: Make changes atomically →