Reading history

SQL Injection and Parameterized Queries Explained

6 min read 0 views

See how SQL injection works and how to stop it with parameterized queries in Python, named placeholders, executemany and allow-lists for column names.

SQL injection is one of the oldest and most damaging security bugs. It happens when a program builds an SQL statement by pasting user input into the text, so a cleverly typed “name” becomes part of the SQL itself. An attacker can then read other people’s data, log in without a password or delete tables. The fix is simple and reliable: parameterized queries. This lesson shows the attack and the fix in Python.

In this lesson you will learn

  • How pasting input into SQL text lets an attacker change the query
  • Writing parameterized queries with ? and named placeholders
  • Inserting many rows safely with executemany
  • Handling column names that cannot be parameters
  • Other layers of defence

You should know the WHERE clause and basic Python. The same ideas apply in PHP, Java, JavaScript and every other language.

The Attack

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE users (id INTEGER PRIMARY KEY, username TEXT, password_hash TEXT, role TEXT);
INSERT INTO users (username, password_hash, role) VALUES
  ('nusrat', 'x9f2...', 'student'),
  ('admin',  'a71c...', 'admin');
""")

def find_user_unsafe(name):
    sql = f"SELECT id, username, role FROM users WHERE username = '{name}'"
    print("SQL sent:", sql)
    return db.execute(sql).fetchall()

print(find_user_unsafe("nusrat"))

# An attacker types this into the username box instead of a name
attack = "' OR '1'='1"
print(find_user_unsafe(attack))

Output

SQL sent: SELECT id, username, role FROM users WHERE username = 'nusrat'
[(1, 'nusrat', 'student')]
SQL sent: SELECT id, username, role FROM users WHERE username = '' OR '1'='1'
[(1, 'nusrat', 'student'), (2, 'admin', 'admin')]
  • The function builds the SQL with an f-string, so whatever the user types becomes part of the statement.
  • For a normal name, the SQL is fine and finds one user.
  • The attacker types ' OR '1'='1. The first quote closes the string early, and the rest adds a condition that is always true. The statement now returns every user, including the admin.
  • In a login form, the same trick can skip the password check. With other inputs an attacker could read different tables or, in some setups, change or delete data.

The Fix: Parameterized Queries

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE users (id INTEGER PRIMARY KEY, username TEXT, password_hash TEXT, role TEXT);
INSERT INTO users (username, password_hash, role) VALUES
  ('nusrat', 'x9f2...', 'student'),
  ('admin',  'a71c...', 'admin');
""")

def find_user(name):
    # The ? is a placeholder; the value travels separately from the SQL text
    return db.execute("SELECT id, username, role FROM users WHERE username = ?",
                      (name,)).fetchall()

print(find_user("nusrat"))
print(find_user("' OR '1'='1"))         # treated as a strange username, finds nothing

# Named placeholders and many rows at once
db.executemany("INSERT INTO users (username, role) VALUES (:u, :r)",
               [{"u": "O'Brien", "r": "student"}, {"u": "tania", "r": "student"}])
print(db.execute("SELECT username FROM users WHERE role = :r ORDER BY id",
                 {"r": "student"}).fetchall())

# Placeholders cannot stand for column or table names: use an allow-list
def sort_users(column):
    allowed = {"username", "role", "id"}
    if column not in allowed:
        raise ValueError(f"cannot sort by {column!r}")
    return db.execute(f"SELECT username FROM users ORDER BY {column}").fetchall()

print(sort_users("username"))
try:
    sort_users("id; DROP TABLE users")
except ValueError as e:
    print("Rejected:", e)

Output

[(1, 'nusrat', 'student')]
[]
[('nusrat',), ("O'Brien",), ('tania',)]
[("O'Brien",), ('admin',), ('nusrat',), ('tania',)]
Rejected: cannot sort by 'id; DROP TABLE users'
  • The SQL contains a ? placeholder, and the value is passed separately as (name,). The database receives the statement and the data in separate parts, so the data can never become SQL.
  • The attack string is now just an unusual username. No user has that name, so the result is empty.
  • Named placeholders such as :u and :r take their values from a dictionary, which reads well when there are many values.
  • Parameters also fix a normal bug: the name O'Brien contains a quote that would break a pasted-together statement, but goes in safely as a parameter.
  • Placeholders can stand for values only, not for table or column names. For a sort column chosen by the user, check it against a fixed allow-list, as sort_users does. Anything not on the list is rejected.

Placeholders in Other Languages

Language / libraryExample
Python sqlite3cur.execute("... WHERE id = ?", (5,))
Python psycopg (PostgreSQL)cur.execute("... WHERE id = %s", (5,))
PHP PDO$stmt = $pdo->prepare("... WHERE id = :id"); $stmt->execute(['id' => 5]);
Java JDBCPreparedStatement ps = conn.prepareStatement("... WHERE id = ?"); ps.setInt(1, 5);
Node.js (mysql2)conn.execute("... WHERE id = ?", [5])

In psycopg the placeholder is written %s, but it is still a real parameter, not Python string formatting. Never use the % operator or f-strings to put values into SQL yourself.

Defence in Depth

  • Least privilege: the database account used by a website should not have permission to drop tables or read tables it does not need.
  • Validate input: check that an age is a number and an email looks like an email. This improves data quality but does not replace parameters.
  • Hide error details: show users a friendly message, and keep the full database error in your logs.
  • Use an ORM or query builder carefully. They use parameters by default, but most still allow raw SQL, where the same rules apply.

Common Mistakes

  1. “Escaping” quotes by hand with replace("'", "''"). It is easy to miss a case; parameters handle every case.
  2. Trusting data from your own database or from hidden form fields. Anything that came from a user at some point can carry an attack.
  3. Parameterizing the value but pasting in the column name from user input.
  4. Writing (name) instead of (name,) in Python. Without the comma it is not a tuple, so sqlite3 treats the string as a sequence of characters and reports the wrong number of bindings.

Practice Exercises

Exercise 1. Rewrite this unsafe line with a parameter: db.execute(f"DELETE FROM users WHERE id = {user_id}").

Show answer
db.execute("DELETE FROM users WHERE id = ?", (user_id,))

Exercise 2. Write a safe search for usernames that start with whatever the user typed.

Show answer
rows = db.execute("SELECT username FROM users WHERE username LIKE ? || '%'",
                  (prefix,)).fetchall()

The % wildcard stays in the SQL; only the user’s text is a parameter. If the user may type % or _ themselves, escape those characters and add an ESCAPE clause.

Frequently Asked Questions

Are stored procedures safe from SQL injection?

Only if they use parameters inside. A stored procedure that builds dynamic SQL by joining strings is just as vulnerable as application code.

Do parameterized queries make my app slower?

No. They are often faster, because the database can reuse the plan for a statement whose text does not change between calls.

Summary

  • Never paste user input into SQL text.
  • Use placeholders such as ? or :name and pass values separately.
  • Placeholders work for values, not identifiers; use an allow-list for column names.
  • Add least privilege, validation and safe error messages as extra layers.

Next: SQL Query Optimization.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *