Parameterized SQL
Separate the query from its values
A parameterized query supplies a fixed SQL statement and a separate collection of values to the database driver. The driver binds each value to a placeholder. This lets a name with punctuation remain a name instead of changing the statement. In Python sqlite3, the question mark is one supported placeholder style; other drivers may use different markers.
A catalog lookup
This standalone local Python example uses SQLite in memory. It creates two public catalog entries, binds one title, and returns just its matching price. No external database is needed. The trailing comma creates a one-element tuple.
import sqlite3with sqlite3.connect(":memory:") as db: db.execute("CREATE TABLE books (title TEXT, price INTEGER)") db.executemany("INSERT INTO books VALUES (?, ?)", [("Sam's Guide", 12), ("Atlas", 20)]) row = db.execute("SELECT price FROM books WHERE title = ?", ("Sam's Guide",)).fetchone() print(row[0])db.close()Expected output: 12. The context manager handles transaction completion; explicit close releases the connection.
Structural choices are different
Placeholders stand for values, not table names, column names or SQL keywords. If the interface offers sorting by title or price, map each supported choice to a complete, fixed query owned by the application; reject unknown choices. Keep values bound even when the user selected an allowed filter. Do not construct SQL by inserting raw request text.
What binding does not guarantee
A bound value may still be too long, the request may lack permission, or a query may return excessive records. Use business validation, access controls, restricted database permissions and resource limits as separate safeguards. Use the correct binding API even when inputs were checked earlier. A stored procedure or ORM is not automatically safe if it constructs dynamic SQL from raw strings.
Practice: choose a lookup
In the local catalog example, predict the result for Atlas (20) and an absent title (fetchone returns None). Modify the caller to handle no match without reading row[0]. Explain which parts are fixed SQL and which parts are data. Source: OWASP SQL Injection Prevention and Python sqlite3 documentation.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Parameterized SQL — knowledge check
Apply defensive data handling to a fictional bookstore.
How should a title be supplied to SQLite execute?
What does (title,) represent in the Python example?
How should a user select sorting by price or title?
The bound lookup has no matching title. What does fetchone return?
Which concern remains after query parameters are bound?