Nexus Void Research

SQL Injection, CWE-89, Parameterized Queries, Prepared Statements, Node.js, Python, Java, Spring Boot, How-to

How to Prevent SQL Injection in Node.js, Python and Java

How to prevent SQL injection: parameterised queries in Node.js, Python, Java, PHP and C#, safe ORM use, allow-listed ORDER BY, and defence in depth.

To prevent SQL injection, never build SQL by concatenating or formatting user input into a query string. Use parameterised queries (prepared statements) so the database treats input as data, never as code: ? or $1 placeholders in Node.js, %s or ? parameters in Python, PreparedStatement in Java. Allow-list anything that cannot be a parameter, such as column names in ORDER BY, and run the app with a least-privilege database user.

SQL injection is one of the oldest web vulnerabilities and still one of the most exploited. MITRE tracks it as CWE-89; the CISA Known Exploited Vulnerabilities catalog lists 33 actively exploited SQL injection CVEs, 9 of them added in 2026 alone, according to our 2026 vulnerability statistics. The fix has been known for decades and is the core of the OWASP SQL Injection Prevention Cheat Sheet. This guide shows it in Node.js, Python, Java, PHP and C#, plus the cases parameters do not cover.

How does SQL injection work?

The application builds a query by pasting user input into SQL:

// Vulnerable
const sql = "SELECT * FROM users WHERE email = '" + req.query.email + "'";
// Vulnerable
const sql = "SELECT * FROM users WHERE email = '" + req.query.email + "'";
// Vulnerable
const sql = "SELECT * FROM users WHERE email = '" + req.query.email + "'";

An attacker sends ' OR '1'='1 as the email, and the query becomes SELECT * FROM users WHERE email = '' OR '1'='1', which returns every user. Other payloads read other tables, bypass logins, modify data or, on some databases, run commands on the server. The root cause is always the same: input is mixed into the code of the query.

Prevent SQL injection in Node.js

Pass values separately from the SQL text.

// node-postgres (pg)
const { rows } = await pool.query(
  "SELECT * FROM users WHERE email = $1",
  [req.query.email]
);

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

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

// mysql2
const [rows] = await conn.execute(
  "SELECT * FROM users WHERE email = ?",
  [req.query.email]
);

ORMs and query builders are safe when you use their normal APIs, and unsafe when you use their raw-string escape hatches with interpolation:

Library

Safe

Unsafe

Prisma

prisma.$queryRaw tagged template, normal client methods

prisma.$queryRawUnsafe with string concatenation

Sequelize

Model methods; query() with replacements or bind

query() with template strings containing input

Knex

Builder methods; whereRaw("email = ?", [email])

whereRaw with interpolated strings

TypeORM

Repository methods; .where("u.email = :email", { email })

.where with template strings containing input

Prevent SQL injection in Python

Use the driver's parameter substitution, never Python string formatting.

# sqlite3
cur.execute("SELECT * FROM users WHERE email = ?", (email,))

# psycopg (PostgreSQL): %s here is a placeholder, not string formatting
cur.execute("SELECT * FROM users WHERE email = %s", (email,))

# SQLAlchemy
from sqlalchemy import text
conn.execute(text("SELECT * FROM users WHERE email = :email"), {"email": email})
# sqlite3
cur.execute("SELECT * FROM users WHERE email = ?", (email,))

# psycopg (PostgreSQL): %s here is a placeholder, not string formatting
cur.execute("SELECT * FROM users WHERE email = %s", (email,))

# SQLAlchemy
from sqlalchemy import text
conn.execute(text("SELECT * FROM users WHERE email = :email"), {"email": email})
# sqlite3
cur.execute("SELECT * FROM users WHERE email = ?", (email,))

# psycopg (PostgreSQL): %s here is a placeholder, not string formatting
cur.execute("SELECT * FROM users WHERE email = %s", (email,))

# SQLAlchemy
from sqlalchemy import text
conn.execute(text("SELECT * FROM users WHERE email = :email"), {"email": email})

The dangerous versions look almost the same:

cur.execute(f"SELECT * FROM users WHERE email = '{email}'")      # vulnerable
cur.execute("SELECT * FROM users WHERE email = '%s'" % email)     # vulnerable
cur.execute(f"SELECT * FROM users WHERE email = '{email}'")      # vulnerable
cur.execute("SELECT * FROM users WHERE email = '%s'" % email)     # vulnerable
cur.execute(f"SELECT * FROM users WHERE email = '{email}'")      # vulnerable
cur.execute("SELECT * FROM users WHERE email = '%s'" % email)     # vulnerable

Django: the ORM (User.objects.filter(email=email)) is safe. With raw() and cursor.execute(), always pass params, and avoid extra() and RawSQL with interpolated input.

Prevent SQL injection in Java and Spring Boot

Use PreparedStatement and bind every value.

String sql = "SELECT * FROM users WHERE email = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setString(1, email);
    ResultSet rs = ps.executeQuery();
}
String sql = "SELECT * FROM users WHERE email = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setString(1, email);
    ResultSet rs = ps.executeQuery();
}
String sql = "SELECT * FROM users WHERE email = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setString(1, email);
    ResultSet rs = ps.executeQuery();
}
// Spring JdbcTemplate
List<User> users = jdbcTemplate.query(
    "SELECT * FROM users WHERE email = ?", userRowMapper, email);

// JPA / Hibernate: named parameters, never concatenated JPQL
TypedQuery<User> q = em.createQuery(
    "SELECT u FROM User u WHERE u.email = :email", User.class);
q.setParameter("email", email);
// Spring JdbcTemplate
List<User> users = jdbcTemplate.query(
    "SELECT * FROM users WHERE email = ?", userRowMapper, email);

// JPA / Hibernate: named parameters, never concatenated JPQL
TypedQuery<User> q = em.createQuery(
    "SELECT u FROM User u WHERE u.email = :email", User.class);
q.setParameter("email", email);
// Spring JdbcTemplate
List<User> users = jdbcTemplate.query(
    "SELECT * FROM users WHERE email = ?", userRowMapper, email);

// JPA / Hibernate: named parameters, never concatenated JPQL
TypedQuery<User> q = em.createQuery(
    "SELECT u FROM User u WHERE u.email = :email", User.class);
q.setParameter("email", email);

Spring Data repository methods (findByEmail) and @Query with :param bindings are safe. String-built JPQL or createNativeQuery with concatenation is not; injection works in JPQL too.

Prevent SQL injection in PHP and C#

// PHP PDO
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
// PHP PDO
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
// PHP PDO
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
// C# ADO.NET
using var cmd = new SqlCommand("SELECT * FROM users WHERE email = @email", conn);
cmd.Parameters.Add("@email", SqlDbType.NVarChar, 254).Value = email;
// C# ADO.NET
using var cmd = new SqlCommand("SELECT * FROM users WHERE email = @email", conn);
cmd.Parameters.Add("@email", SqlDbType.NVarChar, 254).Value = email;
// C# ADO.NET
using var cmd = new SqlCommand("SELECT * FROM users WHERE email = @email", conn);
cmd.Parameters.Add("@email", SqlDbType.NVarChar, 254).Value = email;

In Entity Framework, LINQ queries and FromSqlInterpolated are parameterised; FromSqlRaw with string concatenation is not.

What about input that cannot be a parameter?

Placeholders work for values, not for identifiers or keywords. Table names, column names and sort direction need an allow-list:

const SORT_COLUMNS = { name: "name", created: "created_at", price: "price" };
const column = SORT_COLUMNS[req.query.sort] ?? "created_at";
const direction = req.query.dir === "asc" ? "ASC" : "DESC";
const sql = `SELECT * FROM products ORDER BY ${column} ${direction} LIMIT $1`;
await pool.query(sql, [limit]);
const SORT_COLUMNS = { name: "name", created: "created_at", price: "price" };
const column = SORT_COLUMNS[req.query.sort] ?? "created_at";
const direction = req.query.dir === "asc" ? "ASC" : "DESC";
const sql = `SELECT * FROM products ORDER BY ${column} ${direction} LIMIT $1`;
await pool.query(sql, [limit]);
const SORT_COLUMNS = { name: "name", created: "created_at", price: "price" };
const column = SORT_COLUMNS[req.query.sort] ?? "created_at";
const direction = req.query.dir === "asc" ? "ASC" : "DESC";
const sql = `SELECT * FROM products ORDER BY ${column} ${direction} LIMIT $1`;
await pool.query(sql, [limit]);

The user picks a key; your code picks the SQL. Never pass the raw value through.

Other cases to handle:

  • LIKE searches: parameterise the value, and escape % and _ in it if users should not use wildcards.

  • IN lists: generate one placeholder per item ($1, $2, $3) or use your driver's array support, such as = ANY($1) in PostgreSQL.

  • Stored procedures are safe only if they do not build dynamic SQL from their arguments inside.

Add defence in depth

Parameterised queries are the fix. These limit the damage if one is missed:

  • Least-privilege database users: the app account should not own the schema, create tables or read tables it does not need. Use separate users for migrations and for runtime.

  • Generic error messages: do not return database errors to users; they help attackers shape payloads.

  • Input validation: check type, length and format (an ID should be an integer, an email should look like an email). Validation is a second layer, not a substitute for parameters.

  • A web application firewall can block common payloads, but attackers routinely bypass pattern filters. Treat it as a backstop.

Do NoSQL databases have injection too?

Yes. MongoDB queries built from untrusted JSON can be manipulated with operators: a login that passes {"password": {"$ne": null}} straight into a query can match any password. Validate that fields are the types you expect (strings, not objects), use schema validation, and never pass raw request bodies into query filters.

How do you find SQL injection in existing code?

  1. Search for string-built queries: +, f-strings, % formatting, template literals and String.format near SELECT, INSERT, UPDATE, DELETE, ORDER BY and raw query methods.

  2. Run static analysis on every pull request, so new string-built queries are flagged before merge.

  3. Check every raw-query escape hatch in your ORM: raw, $queryRawUnsafe, whereRaw, createNativeQuery, FromSqlRaw.

  4. Test in staging with a dynamic scanner or a manual test of each input that reaches the database.

Add string-built queries to your security code review checklist. The browser-side equivalent is covered in how to prevent XSS.

SQL injection prevention checklist

Check

Done when

Parameterised queries everywhere

No user input is concatenated or formatted into SQL

ORM escape hatches reviewed

Raw-query methods only take bound parameters

Identifiers allow-listed

ORDER BY, table and column names map from fixed keys

Least-privilege DB user

Runtime account cannot alter schema or read unrelated data

Errors hidden

Users never see database error text

NoSQL inputs typed

Query filters reject objects where strings are expected

Pull requests scanned

String-built queries are flagged before merge

How does ARGUS find SQL injection?

  1. Rule-based static analysis flags string-built queries and unsafe raw-query calls across languages, with severity and a suggested fix.

  2. AI taint analysis follows user input from the request to the query across files in Python, JavaScript, TypeScript, Ruby, Go, Java and PHP, and shows the path as a file-by-file timeline, so you see where the input enters and where it reaches the database.

  3. Every AI finding is independently challenged and dropped if it cannot be substantiated.

  4. Pull request review comments inline on new string-built queries in the changed lines and requests changes for Critical and High findings before merge.

  5. Fix pull requests: Assign to Agent rewrites the query with parameters, verifies it with a build and a re-scan, and opens a pull request for you to review and merge.

Limits: AI passes run when AI scanning is enabled; pull request review runs on GitHub. See ARGUS SAST, or scan a repository free.

Frequently asked questions

How do you prevent SQL injection?

Use parameterised queries, also called prepared statements, for every query that includes user input, so the database treats the input as data rather than SQL. Allow-list anything that cannot be a parameter, such as column names and sort direction, and use a least-privilege database account as a second layer.

How do you prevent SQL injection in Node.js?

Pass values as parameters: pool.query("... WHERE email = $1", [email]) with node-postgres, or conn.execute("... WHERE email = ?", [email]) with mysql2. In ORMs, use normal query methods or safe raw APIs such as Prisma's $queryRaw tagged template, and avoid unsafe raw methods with string concatenation.

How do you prevent SQL injection in Python?

Use the driver's parameters, never string formatting: cur.execute("... WHERE email = %s", (email,)) with psycopg, ? placeholders with sqlite3, or text() with bound parameters in SQLAlchemy. In Django, the ORM is safe; pass params to raw() and avoid extra() with interpolated input.

How do you prevent SQL injection in Java?

Use PreparedStatement with ? placeholders and setString or similar for every value. In Spring, use JdbcTemplate with arguments, Spring Data repository methods, or @Query with named parameters. In JPA, bind values with setParameter and never concatenate input into JPQL or native queries.

Are ORMs safe from SQL injection?

Mostly, when you use their normal query methods, which parameterise values. Every ORM also has raw-query escape hatches, such as $queryRawUnsafe, whereRaw, raw() or createNativeQuery, that are vulnerable if you build the string from user input. Review every use of those.

Does input validation prevent SQL injection?

Not on its own. Validation and escaping are easy to get wrong and attackers find encodings that slip through. Parameterised queries are the fix; validation of type, length and format is a useful second layer that also catches bugs.

Can a WAF stop SQL injection?

A web application firewall can block many common payloads and buys time, but attackers regularly bypass pattern-based rules with encoding and obfuscation. It is a backstop, not a fix. Parameterised queries in your code remove the vulnerability itself.

Is SQL injection still common in 2026?

Yes. CISA's Known Exploited Vulnerabilities catalog lists 33 SQL injection CVEs with confirmed exploitation, and 9 were added in 2026. It persists in legacy code, raw-query shortcuts in ORMs, dynamic ORDER BY clauses and code generated quickly without review.

DATA SOURCES

CWE-89: https://cwe.mitre.org/data/definitions/89.html ; OWASP SQL Injection Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html ; CISA KEV (Nexus Void analysis)

Liked this post? Share it: