liveBook · Manning

SQL injection

As explained in DuckDB in Action

An SQL injection attack is an attack in which crafted input alters the intended semantics of an SQL statement.

SQL injection occurs when crafted input is concatenated into SQL statement text and changes the query’s intended semantics. Pass user input separately as a parameter instead. section 6.2.3

Use these practical safeguards and distinctions:

  • Keep statement text constant and supply changing values through named or positional parameters. section 6.2.3
  • Avoid concatenating user input into SQL fragments; specially crafted text can alter query semantics. section 6.2.3
  • Use a relational query builder for dynamic query construction where table or column names cannot be parameterized. section 6.2.2

Parameterized filtering with DuckDB

con.execute(""" SELECT count(*) FROM over_10m WHERE "GDP ($ per capita)" > $gdp """, {"gdp": 10000}).fetchone() This returns (20,), while keeping the threshold outside the statement text. section 6.2.3

con.execute("""
SELECT count(*)
FROM over_10m
WHERE "GDP ($ per capita)" > $gdp  #1
""", {
  "gdp":10000  #2
}).fetchone()  #3

Inspect the executable pattern for separating SQL text, named input, and result retrieval. section 6.2.3

How DuckDB in Action covers it

How deep it goes
Explains altered query semantics, parameter separation, prepared statements, and execution, but does not develop attack payloads.
Examples
Demonstrates a named GDP parameter in DuckDB and retrieves a single aggregate result through fetchone.
What it assumes
Assumes basic SQL and Python familiarity while introducing parameter placeholders and DB-API result retrieval.
What you can do after
Apply it via DuckDB execute and parameterized queries to reduce SQL injection risk from user input.
How it connects
Connects SQL injection with parameterized queries, prepared statements, string concatenation, and relational query builders.

Also explained in

Compare how 9 books explain SQL injection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of DuckDB in Action. The section links point to the parts of the book it draws on.