SQL injection and parameterized queries

SQL injection happens when untrusted input is pasted into a SQL command so that the input changes the structure of the query. It has been among the most serious and common web vulnerabilities for decades, and is covered by the injection category in the OWASP Top 10. A successful attack can read, change, or delete data.

Python
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (name TEXT, secret TEXT)")
db.executemany("INSERT INTO users VALUES (?, ?)", [("ada", "s3cret-a"), ("bob", "s3cret-b")])


def unsafe(name):
    return db.execute("SELECT name FROM users WHERE name = '" + name + "'").fetchall()


def safe(name):
    return db.execute("SELECT name FROM users WHERE name = ?", (name,)).fetchall()


attack = "' OR '1'='1"
print(unsafe("ada"))
print(unsafe(attack))
print(safe(attack))
Read the full lesson