SQL Injection and Parameterized Queries in Python, Java and Node
SQL injection happens when a program builds an SQL statement by pasting user input into the SQL text. The database cannot tell which part of the text the developer wrote and which part came from the user, so input that contains SQL syntax changes what the query does. It has been one of the most common and most damaging web application flaws for decades, catalogued as CWE-89, and it is almost entirely preventable with one habit: parameterized queries.
Examples use Python 3.10 or later (with the built-in sqlite3 module and psycopg 3 for PostgreSQL), Node.js 22 or later with the pg package, and Java 17 or later with JDBC. The Python and Node.js samples were run against SQLite and PostgreSQL 16; the output shown is real.
The safe way first
With a parameterized query (also called a prepared statement), the SQL text contains a placeholder where each value goes, and the values are sent to the database separately. The database parses the SQL first and only then plugs in the values, so a value can never become SQL syntax, whatever characters it contains.
import sqlite3
def find_user(db, name):
# The ? is a placeholder; the value is sent separately from the SQL text
return db.execute(
"SELECT id, name, email FROM users WHERE name = ?", (name,)
).fetchall()
db = sqlite3.connect("app.db")
print(find_user(db, "Ada"))
print(find_user(db, "O'Brien")) # the apostrophe is just data
[(1, 'Ada', 'ada@example.com')]
[(3, "O'Brien", 'obrien@example.com')]
The name O'Brien contains a single quote, the character SQL uses to end a string. As a parameter it is simply part of the value.
What goes wrong without parameters
Do not do this:
import sqlite3
db = sqlite3.connect("app.db")
name = "O'Brien"
# Do not do this: the value becomes part of the SQL text
query = f"SELECT id, name FROM users WHERE name = '{name}'"
print(query)
try:
db.execute(query)
except sqlite3.OperationalError as err:
print("OperationalError:", err)
# The fix: a placeholder, with the value passed separately
print(db.execute("SELECT id, name FROM users WHERE name = ?", (name,)).fetchall())
SELECT id, name FROM users WHERE name = 'O'Brien'
OperationalError: near "Brien": syntax error
[(3, "O'Brien")]
The apostrophe ended the SQL string early, and the database tried to read Brien' as SQL. Here the result is a syntax error, which is a bug customers with apostrophes in their names will find. The same mechanism is the vulnerability: input written deliberately to close the quote and add its own SQL could change which rows the query returns or what it does to them. The fix is in the last line of the sample: the placeholder version returns the right row.
Every way of building the SQL text from input has this flaw: f-strings, % or .format() in Python, + or template literals in JavaScript, + or String.format in Java.
Placeholders in each language
| Library | Placeholder | Values passed as |
|---|---|---|
Python sqlite3 | ? (or :name) | a tuple, or a dict for named |
Python psycopg (PostgreSQL) | %s (or %(name)s) | a tuple, or a dict |
Java JDBC PreparedStatement | ? | setString, setInt and so on, numbered from 1 |
Node.js pg | $1, $2 | an array |
The %s in psycopg looks like Python string formatting but is not: you pass the values as the second argument to execute, never with the % operator. Do not put quotes around a placeholder; the library handles quoting and types.
Python with PostgreSQL (psycopg)
import os
import psycopg # pip install "psycopg[binary]"
# Connection details come from the environment, e.g.
# DATABASE_URL="postgresql://app_user@localhost/appdb" (password in ~/.pgpass)
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
rows = conn.execute(
"SELECT id, name FROM users WHERE name = %s", ("O'Brien",)
).fetchall()
print(rows)
[(3, "O'Brien")]
Node.js with pg
import pg from "pg"; // npm install pg
// Reads DATABASE_URL from the environment; no credentials in code
const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
try {
const { rows } = await client.query(
"SELECT id, name FROM users WHERE name = $1",
["O'Brien"],
);
console.log(rows);
} finally {
await client.end();
}
[ { id: 3, name: "O'Brien" } ]
Java with JDBC
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class FindUser {
public static void main(String[] args) throws SQLException {
String url = System.getenv("JDBC_URL"); // e.g. jdbc:postgresql://localhost/appdb
String sql = "SELECT id, name FROM users WHERE name = ?";
try (Connection conn = DriverManager.getConnection(
url, System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, "O'Brien"); // parameter 1 is the first ?
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
}
}
}
}
Running it needs the PostgreSQL JDBC driver on the classpath. In all three, the connection details and the password come from environment variables (or a file such as ~/.pgpass that stays out of Git), never from the source code.
What parameters cannot do: identifiers
A placeholder stands for a value. Table names, column names, ASC/DESC and other SQL keywords cannot be parameters. When the user chooses one (a sort column, for example), map their choice to SQL text you wrote, using a fixed allowlist, and reject anything else:
import sqlite3
# Identifiers (table and column names, sort direction) cannot be parameters.
# Map the user's choice to SQL text you wrote yourself.
SORT_COLUMNS = {
"name": "name",
"email": "email",
"newest": "id DESC",
}
def list_users(db, sort):
order_by = SORT_COLUMNS.get(sort)
if order_by is None:
raise ValueError(f"cannot sort by {sort!r}")
# order_by can only be one of the fixed strings above
return db.execute(f"SELECT id, name FROM users ORDER BY {order_by}").fetchall()
db = sqlite3.connect("app.db")
print(list_users(db, "newest"))
try:
list_users(db, "name; anything else")
except ValueError as err:
print("ValueError:", err)
[(3, "O'Brien"), (2, 'Grace'), (1, 'Ada')]
ValueError: cannot sort by 'name; anything else'
The f-string here is safe only because order_by can never be anything but one of the three strings in the dictionary. Never insert the user's text itself.
The same idea applies to LIKE searches: build the pattern as the value, and pass it as a parameter.
import sqlite3
db = sqlite3.connect("app.db")
term = "br" # from a search box
rows = db.execute(
"SELECT name FROM users WHERE name LIKE ? ORDER BY name",
(f"%{term}%",), # the wildcards are part of the VALUE, not the SQL
).fetchall()
print(rows)
[("O'Brien",)]
Users can still type % or _ as wildcards in their search; that cannot change the query's structure, but if it matters, escape them in the value and add an ESCAPE clause.
Why escaping is not the fix
"Escaping" means doubling quotes or adding backslashes so that input cannot end a string. It fails in practice: the rules differ between databases, settings and character encodings, it does nothing for numbers and identifiers that are not quoted, and one forgotten call reopens the hole. Parameterization removes the problem instead of patching around it. The OWASP SQL Injection Prevention Cheat Sheet puts parameterized queries first among its primary defenses and strongly discourages escaping input by hand. Its companion, the Query Parameterization Cheat Sheet, shows the syntax for many more languages.
Defense in depth
Parameterized queries are the fix. These limit the damage of any mistake that remains:
- Least privilege. Connect your application with a database user that can read and write the tables it needs, and nothing more. It should not own the tables, so it cannot drop or alter them:
Connected as that user, an attempt to drop the table fails with-- Run as the database owner. Set the role's password separately (\password app_user). CREATE ROLE app_user LOGIN; GRANT CONNECT ON DATABASE appdb TO app_user; GRANT USAGE ON SCHEMA public TO app_user; GRANT SELECT, INSERT, UPDATE, DELETE ON users TO app_user;ERROR: must be owner of table users, and emptying it withTRUNCATEfails withpermission denied for table users. Run migrations with a separate, more privileged account. - Validate input at the boundary. Check type, length and range, and use allowlists for fixed choices. Validation reduces what reaches the database but does not replace parameters:
O'Brienis a perfectly valid name. - Do not show database errors to users. Log the details on the server and return a generic message.
- Watch the escape hatches. ORMs and query builders parameterize by default, but their raw SQL functions do not, and a stored procedure that builds dynamic SQL from its arguments is as vulnerable as application code.
Checking your own code
Search your codebase for SQL keywords next to string building: f"SELECT, "SELECT ... " +, .format( or % on a string containing WHERE, and template literals containing SQL in JavaScript. Each hit should either use placeholders or insert only text from a fixed allowlist. Linters and static analyzers can flag many of these patterns, but they miss some, so review database code with this in mind as well (see finding errors early with static analyzers). For the SQL itself, SQL basics walks through SELECT, JOIN and GROUP BY.