Bind SQL Values with Placeholders
Core idea
Keep SQL syntax fixed and pass data separately. SQLite supports ? placeholders with a sequence, and :name placeholders with a mapping. The driver binds values so an apostrophe in text stays data, not SQL syntax. executemany applies a parameterized data-changing statement to multiple parameter sets. Placeholders cannot substitute table or column identifiers.
import sqlite3from contextlib import closingwith closing(sqlite3.connect(":memory:", autocommit=False)) as db: db.execute('CREATE TABLE labels (name TEXT)') name = "O'Brien" db.execute('INSERT INTO labels VALUES (?)', (name,)) print(db.execute('SELECT name FROM labels WHERE name = ?', (name,)).fetchone()[0])A one-element tuple needs a trailing comma. The apostrophe stays part of the text.
Use named parameters for multiple rows
import sqlite3from contextlib import closingwith closing(sqlite3.connect(":memory:", autocommit=False)) as db: db.execute('CREATE TABLE stock (code TEXT, qty INTEGER)') db.executemany('INSERT INTO stock VALUES (:code, :qty)', [{'code':'A','qty':3}, {'code':'B','qty':8}]) row = db.execute('SELECT code FROM stock WHERE qty >= :minimum', {'minimum':5}).fetchone() print(row[0])Named keys match the placeholders; the threshold remains a value.
Common mistake
Do not interpolate user values into SQL using f-strings or concatenation. For dynamic identifiers choose from a fixed allowlist of trusted SQL fragments. Bound values still need domain validation.
Practice
Insert a name containing quotes and a name containing spaces, then select each with a bound parameter. Inspect the returned values.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Parameterized SQL
Check your understanding of parameterized sql.
What is printed?
import sqlite3from contextlib import closingwith closing(sqlite3.connect(":memory:", autocommit=False)) as db: print(db.execute("SELECT ?", ("a'b",)).fetchone()[0])What is printed?
import sqlite3from contextlib import closingwith closing(sqlite3.connect(":memory:", autocommit=False)) as db: print(db.execute('SELECT :qty * 2', {'qty':4}).fetchone()[0])What can a SQL placeholder represent?
Which parameter fits a single ? placeholder?