SoftwareSideHustles
How-To

How to Prevent SQL Injection With Parameterized Queries (Python, Node.js, Java, PHP)

What SQL injection is, why string formatting and escaping are not enough, and how to write parameterized queries in Python, Node.js, Java, PHP and C# — including LIKE searches, IN lists and dynamic column names.

By Software Side Hustles Editorial Team · Published · Updated · 4 min read

Quick answer: never build SQL by inserting user input into the query string. Pass values separately as parameters: cursor.execute("SELECT * FROM users WHERE email = %s", (email,)) in Python (psycopg), pool.query("... WHERE email = $1", [email]) in Node.js (pg), or a PreparedStatement with ? in Java. The database driver sends the value as data, so it can never be interpreted as SQL.

What is SQL injection?

python
# Vulnerable
email = request.args["email"]
cursor.execute(f"SELECT * FROM users WHERE email = '{email}'")

If someone submits ' OR '1'='1, the query becomes:

sql
SELECT * FROM users WHERE email = '' OR '1'='1'

which returns every user. Depending on the database, permissions and driver, an attacker may be able to read other tables, modify data or, in poorly configured systems, run commands. SQL injection has been in the OWASP Top 10 for as long as the list has existed, and it is still found in new code — including code produced by AI assistants.

How do I write a parameterized query in Python?

python
# sqlite3 uses ? placeholders
cur.execute("SELECT id, name FROM users WHERE email = ?", (email,))
# psycopg (PostgreSQL) uses %s placeholders — but NOT Python % formatting
cur.execute("SELECT id, name FROM users WHERE email = %s", (email,))
# named parameters
cur.execute("SELECT id FROM users WHERE email = %(email)s", {"email": email})

Two details catch people out:

  • The parameters must be a sequence, so a single value needs a trailing comma: (email,). Passing (email) is just email in brackets.
  • "... = %s" % email looks almost identical to cur.execute("... = %s", (email,)) but is string formatting — and vulnerable. The difference is whether the value is passed to execute or into the string.

With SQLAlchemy, use text("... WHERE email = :email") with {"email": email}, or the ORM query builder.

How do I write a parameterized query in Node.js?

javascript
// node-postgres (pg)
const { rows } = await pool.query("SELECT id, name FROM users WHERE email = $1", [email]);
// mysql2
const [rows2] = await conn.execute("SELECT id, name FROM users WHERE email = ?", [email]);

Beware of template literals: pool.query(`SELECT * FROM users WHERE email = '${email}'`) is string concatenation with nicer syntax, and fully injectable. Tagged-template libraries (such as postgres, or Prisma's $queryRaw) are safe because the tag receives the values separately; $queryRawUnsafe with an interpolated string is not.

How do I write a parameterized query in Java?

java
String sql = "SELECT id, name FROM users WHERE email = ?";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, email);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) { /* ... */ }
}
}

With Spring's JdbcTemplate or JdbcClient, use ? or named parameters (:email) and pass values with .param(...). In JPA, use setParameter, never string-built JPQL.

PHP and C#

php
$stmt = $pdo->prepare("SELECT id, name FROM users WHERE email = ?");
$stmt->execute([$email]);
csharp
using var cmd = new SqlCommand("SELECT id, name FROM users WHERE email = @email", conn);
cmd.Parameters.AddWithValue("@email", email);

Why escaping is not enough

Escaping quotes by hand (email.replace("'", "''")) depends on knowing every special case for your database, character set and SQL mode. Historic bypasses have used multi-byte character sets, backslash handling and numeric contexts where no quotes are involved at all (WHERE id = 1 OR 1=1). Parameters avoid the whole category because the value never becomes part of the SQL text.

Tricky cases: LIKE, IN and dynamic columns

LIKE searches — put the wildcards in the value, not the SQL:

python
cur.execute("SELECT * FROM products WHERE name ILIKE %s", (f"%{term}%",))

If users should not be able to type their own % and _ wildcards, escape those characters in term first.

IN lists — generate one placeholder per value:

python
ids = [3, 7, 9]
placeholders = ", ".join(["%s"] * len(ids))
cur.execute(f"SELECT * FROM orders WHERE id IN ({placeholders})", ids)

Only placeholders are interpolated here, never values. PostgreSQL also supports WHERE id = ANY(%s) with a list parameter.

Dynamic column names or sort order — identifiers cannot be parameters. Use an allowlist:

python
SORTABLE = {"name": "name", "created": "created_at"}
column = SORTABLE.get(request.args.get("sort"), "created_at")
direction = "DESC" if request.args.get("dir") == "desc" else "ASC"
cur.execute(f"SELECT * FROM users ORDER BY {column} {direction} LIMIT %s", (limit,))

The user chooses a key; your code chooses the SQL.

Defence in depth

Parameterized queries are the fix. These reduce the damage if something slips through:

  • Least privilege: the application's database user should not own the schema or have rights it does not need.
  • Avoid dynamic SQL in stored procedures: building SQL inside a procedure with string concatenation is just as vulnerable.
  • Watch second-order injection: data stored safely can be injected later if some other code concatenates it into a query.
  • Test it: include inputs such as ' OR '1'='1 and Robert'); DROP TABLE students;-- in your tests, and run a scanner such as sqlmap against staging environments you own.

Frequently asked questions

Do ORMs prevent SQL injection?

Their query builders do. Their raw-SQL escape hatches (raw(), $queryRawUnsafe, text() with f-strings) do not, unless you pass parameters.

Are prepared statements and parameterized queries the same?

Close enough for security purposes. A prepared statement is compiled once and executed with parameters; some drivers parameterize without a separate prepare step. Both keep data out of the SQL text.

Is input validation enough to stop SQL injection?

No. Validate input for correctness, but use parameters for safety. Many legitimate values — names like O'Brien, for example — contain quotes.

Where this skill pays off

Our free query parameters vs string formatting exercise puts two AI-written lookups side by side; one is injectable. Security review of AI-generated code is some of the most valuable evaluation work there is — see how to evaluate AI-generated code, step six.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy