Passing values safely
After this: Pass values with a placeholder, and see what a glued query lets the user do.
On this page · 5 sections · 4 checks
A school app has a search box. The user types a name, and the program shows the student with that name. The program has the typed text in a variable, typed, and needs a SELECT that uses it. How should the text get into the SQL?
Gluing the text in
The first idea most people have is to build the SQL as a string, with the typed text glued into the middle:
glued = "SELECT id, name FROM students WHERE name = '" + typed + "'"String glued = "SELECT id, name FROM students WHERE name = '" + typed + "'";When the user types Ana, the string becomes … WHERE name = 'Ana', and the search works. Now think about what else a user can type.
- A name with a quote in it, such as
O'Brien. The string becomesWHERE name = 'O'Brien'. The quote after the O ends the text early, and SQLite refuses the whole query with a syntax error. - A string written on purpose to change the query:
x' OR '1'='1. Glued in, it gives the SQL below. Run it.
All three students come back. The typed text closed the quote and added a second test, OR '1'='1', which is true for every row. The user did not search for a name; they rewrote the question. This is called . On a real site the same trick can read other people's data or log in without a password.
Passing the value separately
The fix is to keep the typed text out of the SQL text altogether. Write a ? where the value goes, and hand the value to the database next to the SQL, not inside it. The ? is a .
The database first reads the SQL with its ?, so it knows the shape of the question before it sees any value. Then the value arrives, and it can only ever fill that one hole. With the placeholder, x' OR '1'='1 is looked up as a name, quotes and all. No student has that name, so no rows come back.
The program below sends the same typed text both ways and prints how many rows each returns.
import sqlite3
conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")conn.execute("INSERT INTO students (name) VALUES ('Ana'), ('Ben'), ('Chloe')")
typed = "x' OR '1'='1"
glued = "SELECT id, name FROM students WHERE name = '" + typed + "'"print(glued)print(len(conn.execute(glued).fetchall()))
safe = "SELECT id, name FROM students WHERE name = ?"print(len(conn.execute(safe, (typed,)).fetchall()))SELECT id, name FROM students WHERE name = 'x' OR '1'='1' 3 0
import java.sql.*;
public class Main { static int count(ResultSet rs) throws SQLException { int n = 0; while (rs.next()) { n = n + 1; } return n; }
public static void main(String[] args) throws SQLException { Connection conn = DriverManager.getConnection("jdbc:sqlite::memory:"); Statement st = conn.createStatement(); st.execute("CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL)"); st.execute("INSERT INTO students (name) VALUES ('Ana'), ('Ben'), ('Chloe')");
String typed = "x' OR '1'='1";
String glued = "SELECT id, name FROM students WHERE name = '" + typed + "'"; System.out.println(glued); System.out.println(count(st.executeQuery(glued)));
PreparedStatement safe = conn.prepareStatement("SELECT id, name FROM students WHERE name = ?"); safe.setString(1, typed); System.out.println(count(safe.executeQuery())); conn.close(); }}SELECT id, name FROM students WHERE name = 'x' OR '1'='1' 3 0
Here is what it does:
- It builds a table of three students in memory. The name
:memory:gives a database that lives only while the program runs, which is handy for small tests. - It glues the typed text into a SELECT and prints the SQL, so you can see what reaches the database. That query returns
3rows. - It sends a second SELECT with a
?and the typed text as the value. That query returns0rows.
The rule for every program: values from outside, such as typed text, a file or a web form, always go in placeholders. Never glue them into SQL.
The famous version
A well-known example types x'; DROP TABLE students; --. Glued in, that is two statements: the SELECT, and a second one that deletes the whole table.
import sqlite3
conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")conn.execute("INSERT INTO students (name) VALUES ('Ana'), ('Ben'), ('Chloe')")
typed = "x'; DROP TABLE students; --"glued = "SELECT id, name FROM students WHERE name = '" + typed + "'"try: conn.execute(glued)except sqlite3.ProgrammingError as e: print("refused:", e)print(conn.execute("SELECT COUNT(*) FROM students").fetchone()[0])refused: You can only execute one statement at a time. 3
import java.sql.*;
public class Main { public static void main(String[] args) throws SQLException { Connection conn = DriverManager.getConnection("jdbc:sqlite::memory:"); Statement st = conn.createStatement(); st.execute("CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL)"); st.execute("INSERT INTO students (name) VALUES ('Ana'), ('Ben'), ('Chloe')");
String typed = "x'; DROP TABLE students; --"; String glued = "SELECT id, name FROM students WHERE name = '" + typed + "'"; st.executeQuery(glued); ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM students"); rs.next(); System.out.println(rs.getInt(1)); conn.close(); }}3
Python's execute refuses to run more than one statement at a time, so here the table survives and still has 3 rows.In this test, executeQuery ran only the first statement and quietly ignored the rest, so the table survives and still has 3 rows. Other calls of the same driver, such as executeUpdate, do run every statement in the string. Do not count on that. It stops only this famous version, and only for this call. The OR '1'='1' trick above is one statement, and it got through. Placeholders are the protection; nothing else is.
Check yourself
typed holds a name the user typed. Which line sends it to the database safely, so that it can only ever be a name?
The same glued search, on the same three students: Ana, Ben and Chloe. This time someone typed nobody' OR name != 'Ana. This is the SQL that reaches the database. How many rows does it return?
SELECT id, name FROM students WHERE name = 'nobody' OR name != 'Ana'Complete the missing line so that the query runs with the value in city in its placeholder, and the program prints 1 Ana and 3 Chloe.
import sqlite3
conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT NOT NULL)")conn.execute("INSERT INTO students (name, city) VALUES ('Ana', 'Leeds'), ('Ben', 'York'), ('Chloe', 'Leeds')")
city = "Leeds"sql = "SELECT id, name FROM students WHERE city = ? ORDER BY name"____________________ # ← run sql, with city in the placeholderfor student_id, name in rows: print(student_id, name)import java.sql.*;
public class Main { public static void main(String[] args) throws SQLException { Connection conn = DriverManager.getConnection("jdbc:sqlite::memory:"); Statement st = conn.createStatement(); st.execute("CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT NOT NULL)"); st.execute("INSERT INTO students (name, city) VALUES ('Ana', 'Leeds'), ('Ben', 'York'), ('Chloe', 'Leeds')");
String city = "Leeds"; PreparedStatement ps = conn.prepareStatement("SELECT id, name FROM students WHERE city = ? ORDER BY name"); ____________________ // ← put city in the placeholder ResultSet rs = ps.executeQuery(); while (rs.next()) { System.out.println(rs.getInt("id") + " " + rs.getString("name")); } conn.close(); }}A program lets the user pick which table to read, and sends SELECT name FROM ? with the table name as the value. What happens?
Honesty notes
- Show how gluing typed text into SQL lets the person typing change the query, as x' OR '1'='1 does.
- Write a ? placeholder in the SQL and pass the value separately: a tuple in Python, setString on a PreparedStatement in Java.
- Say that a placeholder holds a value only, never a table or column name.
- Say why refusing two statements at once is not a protection: a one-statement injection still gets through.