In this article

When generated code inserts a search string into SQL with interpolation, the value can become part of the query language. Review the exact query shape, replace dynamic values with database parameters, and test that suspicious-looking text is treated as one value. Parameter binding prevents this class of syntax injection; it does not decide whether a user is authorized to see a matched row.

Inspect the generated query boundary

Imagine an assistant adds a search helper to a small inventory service. The happy-path test searches for a known symbol and passes, so a quick review might approve the patch. The important question is how the query is assembled: does the caller's text stay data, or can it change the SQL grammar?

That distinction matters even when the value came from a form, an internal API, or a value already stored in the database. A value's origin does not make string concatenation a safe way to construct query syntax. Python's sqlite3 documentation specifically warns against Python string operations for SQL values and demonstrates parameter substitution instead. sqlite3 — DB-API 2.0 interface for SQLite databases

  • Review query construction and parameter binding, not just the function name or type annotation.

  • Keep the illustrative table and input local; do not paste real customer data into an assistant.

Reproduce the failure with a probe

The following deliberately unsafe example inserts a value between SQL quotes. The probe contains a quote, a condition that is true, and a comment marker. In this SQLite example it changes the WHERE clause, so the query returns rows beyond the requested username. This is a test fixture that exposes a coding flaw, not a payload to try against a system you do not own.

The ordinary input hides the issue because it contains no SQL punctuation. Keep both cases in the test plan: a normal lookup checks intended behavior, while the probe checks that the query's structure cannot be changed by its value.

Unsafe and parameterized lookup
Codepython
import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE users (username TEXT NOT NULL)")
con.executemany("INSERT INTO users VALUES (?)", [("mira",), ("noah",)])

def unsafe_lookup(value):
    sql = f"SELECT username FROM users WHERE username = '{value}'"
    return con.execute(sql).fetchall()

def safe_lookup(value):
    return con.execute(
        "SELECT username FROM users WHERE username = ?", (value,)
    ).fetchall()

probe = "' OR 1=1 --"
print(unsafe_lookup(probe))  # both rows
print(safe_lookup(probe))    # []

    Bind values with a placeholder

    A parameterized statement keeps its SQL text fixed and supplies values separately. In sqlite3, a question-mark placeholder is paired with a sequence whose length matches the placeholders. A named placeholder can instead be paired with a mapping. The driver handles the value as a value rather than reparsing it as SQL syntax. sqlite3 — DB-API 2.0 interface for SQLite databases

    OWASP describes the same boundary: define SQL structure separately from dynamic data and bind data values through the database API. Manually escaping a quote is a weaker substitute because escaping rules vary by database and settings. Escaping is not the code review target when the database API already provides binding. SQL Injection Prevention Cheat Sheet

      Verify ordinary and adversarial inputs

      Run the example and assert behavior rather than checking only that execute returns without an exception. For the probe, the unsafe query returns both inserted rows; the parameterized query returns no rows because no username equals the complete probe string. For a real username, both helpers return only the matching record.

      An independent expected result should come from the fixture, not by calling the implementation twice. For example, assert that the safe lookup of mira yields exactly one mira row, and that the probe yields an empty list. Also verify that the database still contains exactly the two original users after every lookup.

      Independent behavior assertions
      Codepython
      assert safe_lookup("mira") == [("mira",)]
      assert safe_lookup("' OR 1=1 --") == []
      assert con.execute("SELECT COUNT(*) FROM users").fetchone() == (2,)
      • Normal value: safe_lookup("mira") returns [("mira",)].

      • Probe value: safe_lookup("' OR 1=1 --") returns an empty list.

      • The query text remains constant as input values change.

      Handle identifiers and sort choices separately

      A parameter marker represents a data value; it generally cannot stand in for a table name, column name, or SQL keyword. If a feature sorts by a user-selected field, map the accepted option to a fixed application-owned SQL fragment and reject unknown options. Do not paste an arbitrary column name into the query and assume a placeholder will protect it. OWASP calls for allow-listing structural choices. SQL Injection Prevention Cheat Sheet

      Keep the authorization check separate too. Binding a username prevents the value from altering query syntax, but the application must still check whether the caller may read the matching row. A secure query can accurately return data the caller was not entitled to receive if the service omits its access-control condition.

        Tradeoffs and common questions

        Binding can make query code slightly more explicit, and bulk inserts require matching each record to the statement's placeholders. That explicit pairing is useful during review because the SQL structure and values are visible as separate inputs. Database drivers and query builders vary in syntax, so verify the parameter API for the actual library rather than copying sqlite3's question-mark form everywhere.

        Is validating input enough? No; input validation can enforce business rules, but parameterization protects the syntax boundary. Can placeholders select a column? No; choose among fixed known identifiers. Does binding prove access is allowed? No; authorization remains a separate check on the requested resource. Those three distinctions are a stronger review than an assistant's comment saying the query is sanitized. SQL Injection Prevention Cheat Sheet

        A review can make this boundary visible by tracing each value from the request to the database call. If a patch has a query builder, inspect whether it binds the parameter or only formats a string that looks structured. Ask the assistant to identify the exact driver call and then compare it with the library documentation. A generated test that checks only a successful result for mira does not prove the probe remains data. Keep the fixed SQL text and the independently chosen expected rows in the test so a later refactor cannot quietly reintroduce interpolation.

          Sources & editorial notes

          This article was authored with AI using primary-source research and an automated technical review. It has not been reviewed by a human. Code examples are illustrative; run and verify them in your own environment.

          1. sqlite3 — DB-API 2.0 interface for SQLite databases

            Documents Python sqlite3 qmark and named parameter binding and warns against assembling statements with string operations.

          2. SQL Injection Prevention Cheat Sheet

            Recommends parameterized values, fixed allow-lists for SQL structure, and separating syntax protection from other controls.

          nrml promotion

          Put the reading into practice

          Work through an existing repository, review AI suggestions, and test the decisions behind your changes.

          Explore practice problems