Skip to content
BENIBIX Learn

Parameterized Query

Development🔐 SecurityDefences

Also known as Prepared Statement, Bound Parameters, Placeholder Query

A query with blank spots for the data. What a user types can never become a command.

Think of it like

Think of it like a form with boxes. Whatever you write in a box stays in that box.

Example

Jack's login code used to glue the email into the SQL. He switches to a parameterized query, and a quote in an email is now just a quote.

Why it matters

It shuts SQL injection at the root. Filters and escaping only guess at what is dangerous.

Definition

A parameterized query keeps the SQL command and the user's data apart. You write the query with blank spots, like ? or $1. The data is sent on its own and fills those spots. The database never treats that data as part of the command. This is the main defence against SQL injection, and almost every database library supports it.

Example code

python
cur.execute(
    "SELECT * FROM users WHERE email = %s",
    (email,),
)
The query has a blank spot. The email is sent apart from it and can never change the command.
The middle row keeps a blank spot in the query. The attacker's text stays plain data.

Common mistake

Building the query with string formatting and then passing it in. The blank spots must be filled by the library, not by you.

Key takeaways

  1. 1
    Command and data apart. They travel to the database separately.
  2. 2
    Blank spots. A ? or $1 marks where data goes.
  3. 3
    The library fills it. Never paste input in yourself.

Compare