AI Hints
Home›PostgreSQL Tutorial›Postgres from Python
PostgreSQL · Lesson 83 of 120

Parameters and SQL Injection

Never glue strings.

⏱ 2 min read▶ Video at 1:14:43🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

A search box sends whatever the user types. If you glue that text into your SQL, a clever user can change the query itself. That's SQL injection, one of the most common security bugs.

  • User types text
  • Glued into SQL
  • Injection!

Unsafe vs safe

The unsafe version puts the input straight into the SQL string, so the attacker's quote and or one equals one returns every customer. The safe version passes it as a parameter, with percent s. Run it. Five hundred rows leaked, then zero.

injection.pypython
import psycopg

conn = psycopg.connect("postgresql://postgres:postgres@localhost:5432/riverside")

name = "x' OR '1'='1"

unsafe = f"SELECT count(*) FROM customers WHERE last_name = '{name}'"
print("unsafe:", conn.execute(unsafe).fetchone()[0])

safe = "SELECT count(*) FROM customers WHERE last_name = %s"
print("safe:  ", conn.execute(safe, (name,)).fetchone()[0])
Output
unsafe: 500
safe:   0

Safe SQL rules

Always pass values as parameters. Use percent s, or named parameters with percent brackets. Never use f strings or plus to build SQL with user input. For table or column names, use the psycopg sql module.

keyvalue
%spositional
%(name)snamed
f-stringsnever with input
psycopg.sqlsafe identifiers

Summary

Pass values as parameters, never glue them into SQL. Next, transactions in Python.

Key takeaways
  • %s
  • Parameters
  • No f-strings
Next up: Transactions in Python — commit or roll back