Database SQL Injection
What you will learn
- What SQL injection is and why it happens
- How to recognise the vulnerable pattern in code
- The main fix: parameterised queries
- Extra layers of defence
1. The problem
SQL injection happens when a program builds a SQL statement by pasting in text from a user, and that text contains SQL. The database cannot tell which part was written by the programmer and which came from the user, so it runs it all. This is a well-known weakness, and it is easy to avoid.
Here is a small table and a login check written in the vulnerable way (the data is made up):
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, password TEXT)")
con.executemany("INSERT INTO users (name,password) VALUES (?,?)", [("rina","secret1"),("sam","hunter2")])
def login_bad(name, pw):
sql = f"SELECT name FROM users WHERE name = '{name}' AND password = '{pw}'"
return sql, con.execute(sql).fetchall()
Normal use works:
print(login_bad("rina","secret1"))
print(login_bad("rina","wrong"))
("SELECT name FROM users WHERE name = 'rina' AND password = 'secret1'", [('rina',)])
("SELECT name FROM users WHERE name = 'rina' AND password = 'wrong'", [])
Now someone types a password that is really a piece of SQL:
print(login_bad("rina","' OR '1'='1"))
("SELECT name FROM users WHERE name = 'rina' AND password = '' OR '1'='1'", [('rina',), ('sam',)])
Because of OR '1'='1', the condition is always true, and the query returns every user. The attacker never needed the password.
The pasted text also changed the meaning of the statement, not just its data. That is the whole problem.
What the database actually receives. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). The Python above builds the SQL text; here is the text the database gets, as SQL cells. The logins table is a small one of its own (made-up data); Reset data removes it. Normal use, then the injected password:
CREATE TABLE logins (id INTEGER PRIMARY KEY, name TEXT, password TEXT);
INSERT INTO logins (name, password) VALUES ('rina', 'secret1'), ('sam', 'hunter2');
SELECT name FROM logins WHERE name = 'rina' AND password = 'secret1';
SELECT name FROM logins WHERE name = 'rina' AND password = 'wrong';
name
----
rina
(1 row)
name
----
(0 rows)
The pasted statement for the password ' OR '1'='1:
SELECT name FROM logins WHERE name = 'rina' AND password = '' OR '1'='1';
name
----
rina
sam
(2 rows)
CREATE TABLE logins (id INTEGER PRIMARY KEY, name TEXT, password TEXT);
INSERT INTO logins (name, password) VALUES ('rina', 'secret1'), ('sam', 'hunter2');
SELECT name FROM logins WHERE name = 'rina' AND password = 'secret1';
SELECT name FROM logins WHERE name = 'rina' AND password = 'wrong';
name
----
rina
(1 row)
name
----
(0 rows)
The pasted statement for the password ' OR '1'='1:
SELECT name FROM logins WHERE name = 'rina' AND password = '' OR '1'='1';
name
----
rina
sam
(2 rows)
CREATE TABLE logins (id INTEGER PRIMARY KEY, name TEXT, password TEXT);
INSERT INTO logins (name, password) VALUES ('rina', 'secret1'), ('sam', 'hunter2');
SELECT name FROM logins WHERE name = 'rina' AND password = 'secret1';
SELECT name FROM logins WHERE name = 'rina' AND password = 'wrong';
name
----
rina
(1 row)
name
----
(0 rows)
The pasted statement for the password ' OR '1'='1:
SELECT name FROM logins WHERE name = 'rina' AND password = '' OR '1'='1';
name
----
rina
sam
(2 rows)
Because AND binds tighter than OR, the condition reads "(name is rina AND password is empty) OR 1 equals 1", which is always true, so every user comes back.
2. The fix: parameters
Write the SQL with placeholders (? in SQLite) and pass the values separately. The database treats the values as data only, never as SQL.
def login_good(name, pw):
return con.execute("SELECT name FROM users WHERE name = ? AND password = ?", (name, pw)).fetchall()
print(login_good("rina","' OR '1'='1"))
print(login_good("rina","secret1"))
[]
[('rina',)]
The strange password is just a wrong password now. (Real systems never store passwords as plain text; see lesson 8.6.)
3. Injection can do damage, too
Injected text can also add new statements. This function uses executescript, which runs several statements, and builds the text unsafely:
evil = "x'; DROP TABLE users; --"
def find_bad(name):
con.executescript(f"SELECT * FROM users WHERE name = '{name}'")
On a fresh copy of the table:
find_bad(evil)
try:
print(con.execute("SELECT COUNT(*) FROM users").fetchone())
except sqlite3.OperationalError as e:
print("after bad code:", e)
after bad code: no such table: users
The table is gone. Build it again and try the same text as a parameter; it is only a name that matches nobody:
The same attack in SQL cells: the pasted text closes the string, ends the statement, and adds a new one (-- starts a comment that swallows the leftover quote). Running the text as written drops the table:
SELECT * FROM logins WHERE name = 'x'; DROP TABLE logins; --';
id name password
-- ---- --------
(0 rows)
SELECT COUNT(*) FROM logins;
OperationalError: no such table: logins
SELECT * FROM logins WHERE name = 'x'; DROP TABLE logins; --';
id name password
-- ---- --------
(0 rows)
SELECT COUNT(*) FROM logins;
OperationalError: no such table: logins
SELECT * FROM logins WHERE name = 'x'; DROP TABLE logins; --';
id name password
-- ---- --------
(0 rows)
SELECT COUNT(*) FROM logins;
OperationalError: no such table: logins
con.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, password TEXT)")
con.executemany("INSERT INTO users (name,password) VALUES (?,?)", [("rina","secret1"),("sam","hunter2")])
print(con.execute("SELECT * FROM users WHERE name = ?", (evil,)).fetchall())
print(con.execute("SELECT COUNT(*) FROM users").fetchone())
[]
(2,)
4. More layers
Parameters are the main defence. Add others:
- Least privilege (lesson 8.4): the application account should not be allowed to drop tables anyway.
- Validate input: reject values that cannot be right, such as a negative quantity.
- Names that cannot be parameters (table or column names) should come from a fixed list in your code, never from the user.
- Do not show database error messages to visitors; log them privately.
Worked example: spot the danger
| Code | Safe? |
|---|---|
execute(f"SELECT * FROM t WHERE id = {user_id}") |
No: text is pasted into the SQL |
execute("SELECT * FROM t WHERE id = ?", (user_id,)) |
Yes: a parameter |
execute("SELECT * FROM t WHERE name = '" + name + "'") |
No: string joining |
execute("SELECT * FROM " + table) with table from the user |
No: check it against a fixed list first |
Common mistakes
- Building SQL with f-strings,
+or%from user input. - "Cleaning" input by hand (removing quotes) instead of using parameters.
- Trusting hidden form fields, cookies or URLs: they come from the user too.
- Using an account that can do too much.
Key takeaways
- SQL injection happens when user text becomes part of the SQL.
- Use parameterised queries; keep values and SQL apart.
- Add least privilege, input checks and hidden error details.
- Anything that comes from outside your code is user input.
Practice
1. Why did ' OR '1'='1 let anyone log in?
Show answer
It changed the condition into one that is always true, so the query matched every user.
2. What is the main fix?
Show answer
Parameterised queries: SQL with placeholders and the values passed separately.
3. Is execute("... WHERE id = " + str(i)) safe if i comes from a web form?
Show answer
No. Use a placeholder and pass i as a parameter.
4. Why does least privilege help even when you use parameters?
Show answer
If a mistake still lets an attack through, the account can only do limited damage.
5. Why can't a table name be a parameter, and what do you do instead?
Show answer
Placeholders stand for values, not names. Pick the name from a fixed list in your code.
6. What happened to the users table when the unsafe executescript ran the text x'; DROP TABLE users; --?
Show answer
The injected DROP TABLE users ran, and the next query failed with no such table: users.