Programming Search⌘K

Weaknesscore

SQL injection

Also called SQLi, cwe-89.

SQL injection happens when a program puts outside input into the text of an SQL statement, so the database reads part of the input as SQL code and not as a value.

Abstraction
base
OWASP Top 10 (2025)
A05
CWE Top 25 (2025)
rank 2
Languages affected
any-with-sql

Description

A program sends a statement to a database as text. The database parses the text, and the parse decides which parts are SQL keywords, names and operators, and which parts are values. SQL injection happens when the program makes this text by joining fixed SQL with input from outside. The input then goes through the parser together with the code. When the input holds a quote, the quote ends the string literal, and the rest of the input becomes SQL. The program meant one value. The database sees a different statement.

The root cause is that code and data share one channel. The developer knows where the value starts and ends, but the string does not keep this knowledge, and the database cannot get it back. The fix is to keep the two apart until the database has parsed the code (see Fixed code).

An attacker who controls part of a statement can often read data that the query was not meant to return, change or delete rows, or pass a login check. On some database systems, more SQL commands or operating system commands are possible.1 The damage depends on the rights of the database account of the application.

CWE-89 names this weakness. It is a base weakness under CWE-943, improper neutralization of special elements in a data query, and CWE-564 is its variant for Hibernate.1 It is rank 2 of the 2025 CWE Top 25.3 In the OWASP Top 10:2025 it is part of A05:2025 Injection.2

History

Jeff Forristal, writing as rain.forest.puppy, described the problem in Phrack 54 in December 1998.4 His article was about Microsoft web technology. It showed that an ASP page built SQL text with string concatenation, and that Microsoft SQL Server accepted more than one command in a batch, so input could add a second command. The article had no exploit code. Its advice was to double the single quotes in strings and to check that numeric input has only digits. Its first choice was to call stored procedures and to pass the input as parameters.4 Parameters are still the main defence.

Second-order injection

In second-order injection, the input does not change the first query. The program stores it safely, for example with a parameter. Later, other code reads the value from the database, treats it as trusted, and puts it into the text of a second query. The weakness is in the second query. The Python example file shows it with the harmless name O'Brien: the insert is safe, and the later concatenation breaks. Data that comes from the database needs the same care as data that comes from a request.

Blind and time-based injection

An application does not have to show query results or error messages to be exploitable. In blind injection, an attacker sends many requests and infers data from small differences in the response, such as a page that changes or does not change. In time-based injection, the difference is how long the response takes. For a defender, the lesson is that a generic error page and hidden output do not remove the weakness. They only make it slower to exploit. Monitoring can see the pattern: many similar requests with small changes, and queries that take much longer than usual.

Vulnerable code

The function below builds the WHERE clause with +. The second call uses the classic demonstration input x' OR '1'='1. The first quote closes the literal, and OR '1'='1' is true for every row.

This code runs but gives a wrong answer on purpose.

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER, customer TEXT, total REAL)")
db.executemany("INSERT INTO orders VALUES (?, ?, ?)", [(1, "alice", 12.5), (2, "bob", 40.0)])


def find_orders(customer):
    query = "SELECT id, customer, total FROM orders WHERE customer = '" + customer + "'"
    print(query)
    return db.execute(query).fetchall()


print(find_orders("alice"))
print(find_orders("x' OR '1'='1"))
Output
SELECT id, customer, total FROM orders WHERE customer = 'alice'
[(1, 'alice', 12.5)]
SELECT id, customer, total FROM orders WHERE customer = 'x' OR '1'='1'
[(1, 'alice', 12.5), (2, 'bob', 40.0)]

The same weakness appears with every way to build a string: %, format, f-strings, template literals, Sprintf, format! and string interpolation. The example files show it in each language.

Fixed code

A parameterised query has a placeholder where the value goes. The program sends the SQL text and the values in separate arguments.

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER, customer TEXT, total REAL)")
db.executemany("INSERT INTO orders VALUES (?, ?, ?)", [(1, "alice", 12.5), (2, "bob", 40.0)])


def find_orders(customer):
    query = "SELECT id, customer, total FROM orders WHERE customer = ?"
    return db.execute(query, (customer,)).fetchall()


print(find_orders("alice"))
print(find_orders("x' OR '1'='1"))
print(find_orders("O'Brien"))
Output
[(1, 'alice', 12.5)]
[]
[]

The input is now one value. No customer has the name x' OR '1'='1, so the query returns no rows. The name O'Brien also works, with no escaping.

How the protocol keeps them apart

The database parses the statement before it sees the value. In SQLite, the program compiles the text with a placeholder (?, ?NNN, :name, @name or $name) into a prepared statement, and then binds a value to each placeholder.7 In the extended query protocol of PostgreSQL, the client sends the text in a Parse message and the values in a Bind message.6

Parse    SELECT id FROM orders WHERE customer = $1
Bind     $1 = the bytes x' OR '1'='1, as one text value
Execute

The plan of the statement is fixed before the value arrives, so no value can add a clause. The Go documentation says the same of database/sql: the driver sends the SQL text and the parameter separately.8 Some drivers emulate parameters on the client. They escape each value for the exact server and encoding, and the application never builds the text itself.

Why escaping is not enough

Escaping tries to make input safe inside a literal. It fails in several ways. The rules depend on the database and its settings. Escaping does not help where the input is not inside quotes, as in WHERE id = followed by a number, or in a table name. The escape function must also know the character encoding. CVE-2006-2314 is an example: in some multibyte encodings, a backslash byte can be the second byte of a character, so a quote escaped as \' became a character and a bare quote.10 And every developer must remember to escape every value in every query. The OWASP cheat sheet calls manual escaping strongly discouraged.5

Names that cannot be parameters

A placeholder holds a value. It cannot hold a table name, a column name, a keyword such as ASC or DESC, or a list of columns. When such a part must change at run time, choose it from a fixed allow-list in the code, and never copy the input into the text.5 The Python example file maps the input to a column name with a dictionary and rejects every other input.

ORMs and raw queries

An ORM or a query builder makes parameters for the values of its normal API. Each one also has a way to run raw SQL, and the weakness comes back there. In Django, raw() takes the parameters as a second argument, and the documentation says not to use string formatting on raw queries.11 In EF Core, FromSql and ExecuteSql take a FormattableString and make a parameter of each interpolated value, but FromSqlRaw and ExecuteSqlRaw take a plain string.12 HQL and JPQL strings built with + are vulnerable in the same way (CWE-564).1 A stored procedure that is called with bound arguments is safe only if it does not build dynamic SQL from them.5

How to detect it

  • Static analysis with taint tracking. CodeQL follows input from a request to a query function. Its queries are py/sql-injection, js/sql-injection, java/sql-injection, go/sql-injection and cs/sql-injection.13
  • Pattern linters. Ruff rule S608, from flake8-bandit, flags SQL text built with +, %, format or f-strings.14 gosec rules G201 and G202 flag SQL text built with a format string or with concatenation.15 These rules do not know if the value is safe, so they also flag an allow-listed column name. Mark such a line with a comment that names the allow-list.
  • Code review. Search for query calls with one argument, and for SQL keywords next to +, format, ${ or {. Check each raw query method of the ORM.
  • Tests. Put a value with a quote, such as O'Brien, through each input that reaches the database. A syntax error or a missing row shows that the input is part of the SQL text.
  • Logs. SQL syntax errors in production logs often mean that input reached the SQL text.

How to prevent it

  • Bind every value. Use the placeholders of the driver for every value in every statement, including values that come from the database, from files and from other services.5
  • Allow-list the parts that cannot be parameters. Table names, column names and sort directions come from a fixed set in the code.5
  • Keep to the safe API of the ORM. Review each use of raw SQL, and give each raw query its parameters.
  • Run one statement per call. Some APIs refuse more than one statement in a call. Python's sqlite3 raises ProgrammingError for a second statement in execute.9 Keep this behaviour on.
  • Use least privilege. The database account of the application gets only the rights it needs, never administrator rights.5 A read-only feature uses a read-only account. Views and stored procedures can limit the rows and the columns that an account sees. This does not stop the injection, but it limits what an injected statement can do.
  • Validate input as a second layer. A check that an order id has only digits rejects much bad input early. It is not a replacement for parameters, because many valid values, such as names, contain quotes.
  • Show generic errors. Do not send database error messages to the client. This removes help for an attacker, but the weakness stays until the query is fixed.

Real cases

Case Date What happened
TalkTalk October 2015 Attackers used SQL injection on old web pages from Tiscali and got access to customer data. The ICO fined TalkTalk £400,000 in 2016, and said that two earlier attacks of the same kind had gone unnoticed.19
CVE-2021-27101 published 2021-02-16 SQL injection through a crafted Host header in Accellion FTA, a file transfer appliance.17
CVE-2023-34362 published 2023-06-02 SQL injection in the web application of Progress MOVEit Transfer, open to an attacker with no login. The CVE record says that it was exploited in the wild in May and June 2023.16
CVE-2025-26794 published 2025-02-21 Remote SQL injection in the Exim mail server, in a configuration that uses SQLite for hints data with ETRN serialization.18
CVE-2006-2314 2006 The PostgreSQL project showed that escaping a quote as \' is unsafe in some multibyte client encodings, and released fixes.10
PythonGitHub

This code runs but gives a wrong answer on purpose.

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER, customer TEXT, total REAL)")
db.executemany("INSERT INTO orders VALUES (?, ?, ?)", [(1, "alice", 12.5), (2, "bob", 40.0)])


def find_orders(customer):
    query = "SELECT id, customer, total FROM orders WHERE customer = '" + customer + "'"
    print(query)
    return db.execute(query).fetchall()


print(find_orders("alice"))
print(find_orders("x' OR '1'='1"))
Output
SELECT id, customer, total FROM orders WHERE customer = 'alice'
[(1, 'alice', 12.5)]
SELECT id, customer, total FROM orders WHERE customer = 'x' OR '1'='1'
[(1, 'alice', 12.5), (2, 'bob', 40.0)]

The second call returns every row. The quote in the input closes the string literal, and the rest of the input becomes part of the WHERE clause.

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER, customer TEXT, total REAL)")
db.executemany("INSERT INTO orders VALUES (?, ?, ?)", [(1, "alice", 12.5), (2, "bob", 40.0)])


def find_orders(customer):
    query = "SELECT id, customer, total FROM orders WHERE customer = ?"
    return db.execute(query, (customer,)).fetchall()


print(find_orders("alice"))
print(find_orders("x' OR '1'='1"))
print(find_orders("O'Brien"))

SORT_COLUMNS = {"id": "id", "total": "total"}


def list_orders(sort):
    column = SORT_COLUMNS.get(sort)
    if column is None:
        raise ValueError(f"cannot sort by {sort!r}")
    return db.execute(f"SELECT id FROM orders ORDER BY {column} DESC").fetchall()


print(list_orders("total"))
try:
    list_orders("password")
except ValueError as error:
    print(error)
Output
[(1, 'alice', 12.5)]
[]
[]
[(2,), (1,)]
cannot sort by 'password'
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (id INTEGER, name TEXT)")
db.execute("CREATE TABLE audit (name TEXT, action TEXT)")

# Step 1: the sign-up code binds the name, so the insert is safe.
db.execute("INSERT INTO users VALUES (?, ?)", (1, "O'Brien"))

# Step 2: a later job trusts the stored name and builds SQL from it.
(name,) = db.execute("SELECT name FROM users WHERE id = 1").fetchone()
try:
    db.execute("INSERT INTO audit VALUES ('" + name + "', 'login')")
except sqlite3.OperationalError as error:
    print("unsafe:", error)

# The fix: bind the stored value too.
db.execute("INSERT INTO audit VALUES (?, ?)", (name, "login"))
print(db.execute("SELECT * FROM audit").fetchall())
Output
unsafe: near "Brien": syntax error
[("O'Brien", 'login')]
  • Verdict: stdlib. The module sqlite3 binds values to the placeholders ? and :name. Other drivers that follow the database API of PEP 249 use their own placeholder style, such as %s in psycopg.
  • Connection.execute runs one statement and raises ProgrammingError on text with two statements. executescript runs many statements and takes no parameters, so never build its text from input.
  • A placeholder holds a value, not a name. A column name in ORDER BY comes from a fixed dictionary, as in list_orders.
  • The second-order example uses the harmless name O'Brien. The stored value breaks the second query, which shows that the same input could also change it. Values that come from the database need the same binding as values from a request.
  • Ruff rule S608, which comes from flake8-bandit, flags the query built with + in the first example. It also flags the f-string in list_orders, where the allow-list makes it safe. Mark such a line with # noqa: S608 and a comment that names the allow-list.
JavaGitHub

This code runs but gives a wrong answer on purpose.

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class Main {
    // A fake connection that prints what JDBC code sends to a driver.
    // The JDK has no JDBC driver, so the example records the calls.
    static Connection recorder() {
        return (Connection) Proxy.newProxyInstance(
                Main.class.getClassLoader(),
                new Class<?>[] {Connection.class},
                (proxy, method, args) -> switch (method.getName()) {
                    case "createStatement" -> statement(null);
                    case "prepareStatement" -> statement((String) args[0]);
                    default -> null;
                });
    }

    static Object statement(String prepared) {
        List<Object> params = new ArrayList<>();
        Class<?> type = prepared == null ? Statement.class : PreparedStatement.class;
        return Proxy.newProxyInstance(
                Main.class.getClassLoader(),
                new Class<?>[] {type},
                (proxy, method, args) -> {
                    switch (method.getName()) {
                        case "setString" -> params.add(args[1]);
                        case "executeQuery" -> {
                            String sql = prepared == null ? (String) args[0] : prepared;
                            System.out.println("query: " + sql);
                            System.out.println("args:  " + params);
                        }
                        default -> {}
                    }
                    return null;
                });
    }

    public static void main(String[] args) throws SQLException {
        Connection db = recorder();
        String customer = "x' OR '1'='1";

        Statement statement = db.createStatement();
        statement.executeQuery("SELECT id FROM orders WHERE customer = '" + customer + "'");
    }
}
Output
query: SELECT id FROM orders WHERE customer = 'x' OR '1'='1'
args:  []
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class Main {
    // A fake connection that prints what JDBC code sends to a driver.
    // The JDK has no JDBC driver, so the example records the calls.
    static Connection recorder() {
        return (Connection) Proxy.newProxyInstance(
                Main.class.getClassLoader(),
                new Class<?>[] {Connection.class},
                (proxy, method, args) -> switch (method.getName()) {
                    case "createStatement" -> statement(null);
                    case "prepareStatement" -> statement((String) args[0]);
                    default -> null;
                });
    }

    static Object statement(String prepared) {
        List<Object> params = new ArrayList<>();
        Class<?> type = prepared == null ? Statement.class : PreparedStatement.class;
        return Proxy.newProxyInstance(
                Main.class.getClassLoader(),
                new Class<?>[] {type},
                (proxy, method, args) -> {
                    switch (method.getName()) {
                        case "setString" -> params.add(args[1]);
                        case "executeQuery" -> {
                            String sql = prepared == null ? (String) args[0] : prepared;
                            System.out.println("query: " + sql);
                            System.out.println("args:  " + params);
                        }
                        default -> {}
                    }
                    return null;
                });
    }

    public static void main(String[] args) throws SQLException {
        Connection db = recorder();
        String customer = "x' OR '1'='1";

        PreparedStatement statement = db.prepareStatement("SELECT id FROM orders WHERE customer = ?");
        statement.setString(1, customer);
        statement.executeQuery();
    }
}
Output
query: SELECT id FROM orders WHERE customer = ?
args:  [x' OR '1'='1]
  • Verdict: stdlib. JDBC (java.sql) is part of Java SE. PreparedStatement takes SQL text with ? placeholders, and setString, setLong and the other setters bind the values by position. Statement takes complete SQL text and has no parameters.
  • The JDK has no JDBC driver, so the examples use a fake connection, made with java.lang.reflect.Proxy, that prints what it receives.
  • The driver decides how it sends the values. A PostgreSQL driver uses the extended query protocol, where the values travel in their own message. MySQL Connector/J prepares statements on the client by default (useServerPrepStmts=false) and escapes the values in the driver. Both keep the value out of the SQL grammar.
  • JPA and Hibernate have the same weakness when a JPQL or HQL query string is built with +. Use setParameter with named parameters such as :customer. CWE-564 covers SQL injection through Hibernate.
  • CallableStatement binds the arguments of a stored procedure. A procedure that builds dynamic SQL from its arguments is still vulnerable.

This code runs but gives a wrong answer on purpose.

static string FindOrdersSql(string customer) =>
    $"SELECT id FROM orders WHERE customer = '{customer}'";

Console.WriteLine(FindOrdersSql("alice"));
Console.WriteLine(FindOrdersSql("x' OR '1'='1"));
Output
SELECT id FROM orders WHERE customer = 'alice'
SELECT id FROM orders WHERE customer = 'x' OR '1'='1'
// EF Core's FromSql takes a FormattableString, not a string. The compiler
// keeps the format and the arguments apart, and the library turns each
// argument into a parameter. This function does the same thing.
static (string Sql, object?[] Args) Parameterize(FormattableString query)
{
    var names = new object[query.ArgumentCount];
    for (var i = 0; i < names.Length; i++)
    {
        names[i] = $"@p{i}";
    }
    return (string.Format(query.Format, names), query.GetArguments());
}

var customer = "x' OR '1'='1";
var (sql, parameters) = Parameterize($"SELECT id FROM orders WHERE customer = {customer}");
Console.WriteLine($"query: {sql}");
Console.WriteLine($"args:  [{string.Join(", ", parameters)}]");
Output
query: SELECT id FROM orders WHERE customer = @p0
args:  [x' OR '1'='1]
  • Verdict: stdlib. ADO.NET (System.Data.Common) is part of .NET: DbCommand.Parameters holds the values of a command. Each database needs a provider package, such as Microsoft.Data.Sqlite or Npgsql.
  • With Microsoft.Data.Sqlite, write $customer in CommandText and call command.Parameters.AddWithValue("$customer", customer).
  • An interpolated string $"..." that is a string puts the input into the SQL text, as in the first example.
  • EF Core has two families of methods. FromSql, FromSqlInterpolated and ExecuteSql take a FormattableString, and they turn each interpolated value into a parameter, as in the second example. FromSqlRaw, SqlQueryRaw and ExecuteSqlRaw take a string, so an interpolated string is already plain text when they get it.
  • A parameter cannot hold a table or a column name. Choose such names from a fixed list.
  • No example here uses a real database: the provider packages were not in the local NuGet cache when the examples were recorded.
JavaScriptGitHub

This code runs but gives a wrong answer on purpose.

import { DatabaseSync } from "node:sqlite";

const db = new DatabaseSync(":memory:");
db.exec("CREATE TABLE orders (id INTEGER, customer TEXT, total REAL)");
const insert = db.prepare("INSERT INTO orders VALUES (?, ?, ?)");
insert.run(1, "alice", 12.5);
insert.run(2, "bob", 40.0);

function findOrders(customer) {
  const query = `SELECT id, customer FROM orders WHERE customer = '${customer}'`;
  return db.prepare(query).all();
}

console.log(JSON.stringify(findOrders("alice")));
console.log(JSON.stringify(findOrders("x' OR '1'='1")));
Output
[{"id":1,"customer":"alice"}]
[{"id":1,"customer":"alice"},{"id":2,"customer":"bob"}]
import { DatabaseSync } from "node:sqlite";

const db = new DatabaseSync(":memory:");
db.exec("CREATE TABLE orders (id INTEGER, customer TEXT, total REAL)");
const insert = db.prepare("INSERT INTO orders VALUES (?, ?, ?)");
insert.run(1, "alice", 12.5);
insert.run(2, "bob", 40.0);

const byCustomer = db.prepare("SELECT id, customer FROM orders WHERE customer = ?");

console.log(JSON.stringify(byCustomer.all("alice")));
console.log(JSON.stringify(byCustomer.all("x' OR '1'='1")));

const byName = db.prepare("SELECT id FROM orders WHERE customer = :customer AND total > :min");
console.log(JSON.stringify(byName.all({ customer: "bob", min: 10 })));
Output
[{"id":1,"customer":"alice"}]
[]
[{"id":2}]
  • Verdict: stdlib. Node.js has the module node:sqlite. prepare compiles the SQL text, and all, get and run bind the arguments to ? or to named parameters such as :customer.
  • A template literal is not a parameterised query. ${customer} puts the text of the input into the SQL text before prepare sees it.
  • Database clients on npm, such as pg and mysql2, take the SQL text and an array of values. The placeholder syntax is $1 for pg and ? for mysql2.
  • A tagged template, such as the sql tag of some query builders, can be safe: the tag function gets the strings and the values apart and binds the values. A plain template literal does not.

This code runs but gives a wrong answer on purpose.

package main

import (
	"database/sql"
	"database/sql/driver"
	"fmt"
	"io"
)

// recorder is a fake driver. It prints what database/sql sends to a
// driver, so the example needs no database server and no cgo.
type recorder struct{}

func (recorder) Open(string) (driver.Conn, error) { return conn{}, nil }

type conn struct{}

func (conn) Prepare(query string) (driver.Stmt, error) { return stmt{query}, nil }
func (conn) Close() error                              { return nil }
func (conn) Begin() (driver.Tx, error)                 { return nil, driver.ErrSkip }

type stmt struct{ query string }

func (s stmt) Close() error  { return nil }
func (s stmt) NumInput() int { return -1 }
func (s stmt) Exec([]driver.Value) (driver.Result, error) {
	return nil, driver.ErrSkip
}
func (s stmt) Query(args []driver.Value) (driver.Rows, error) {
	fmt.Printf("query: %s\nargs:  %q\n", s.query, args)
	return rows{}, nil
}

type rows struct{}

func (rows) Columns() []string         { return []string{"id"} }
func (rows) Close() error              { return nil }
func (rows) Next([]driver.Value) error { return io.EOF }

func main() {
	sql.Register("recorder", recorder{})
	db, _ := sql.Open("recorder", "")
	customer := "x' OR '1'='1"

	query := fmt.Sprintf("SELECT id FROM orders WHERE customer = '%s'", customer)
	rows, _ := db.Query(query)
	rows.Close()
}
Output
query: SELECT id FROM orders WHERE customer = 'x' OR '1'='1'
args:  []
package main

import (
	"database/sql"
	"database/sql/driver"
	"fmt"
	"io"
)

// recorder is a fake driver. It prints what database/sql sends to a
// driver, so the example needs no database server and no cgo.
type recorder struct{}

func (recorder) Open(string) (driver.Conn, error) { return conn{}, nil }

type conn struct{}

func (conn) Prepare(query string) (driver.Stmt, error) { return stmt{query}, nil }
func (conn) Close() error                              { return nil }
func (conn) Begin() (driver.Tx, error)                 { return nil, driver.ErrSkip }

type stmt struct{ query string }

func (s stmt) Close() error  { return nil }
func (s stmt) NumInput() int { return -1 }
func (s stmt) Exec([]driver.Value) (driver.Result, error) {
	return nil, driver.ErrSkip
}
func (s stmt) Query(args []driver.Value) (driver.Rows, error) {
	fmt.Printf("query: %s\nargs:  %q\n", s.query, args)
	return rows{}, nil
}

type rows struct{}

func (rows) Columns() []string         { return []string{"id"} }
func (rows) Close() error              { return nil }
func (rows) Next([]driver.Value) error { return io.EOF }

func main() {
	sql.Register("recorder", recorder{})
	db, _ := sql.Open("recorder", "")
	customer := "x' OR '1'='1"

	rows, _ := db.Query("SELECT id FROM orders WHERE customer = ?", customer)
	rows.Close()
}
Output
query: SELECT id FROM orders WHERE customer = ?
args:  ["x' OR '1'='1"]
  • Verdict: stdlib. The package database/sql defines the API, and a driver package connects it to a database. Query, QueryRow and Exec take the SQL text and then the arguments.
  • The Go distribution has no database driver, so the examples register a fake driver that prints what it receives. With Sprintf, the driver gets one string with the input inside it and no arguments. With a placeholder, it gets the SQL text and the value apart.
  • A real driver sends the value apart from the text, or binds it in the database library. The placeholder syntax belongs to the driver: ? for MySQL and SQLite drivers, $1 for PostgreSQL drivers.
  • db.Prepare makes a statement once for many calls. db.Query with arguments also prepares the statement, unless the driver can send the text and the arguments in one step.
  • The linter gosec reports SQL text built with Sprintf or + (rules G201 and G202).
RustGitHub

This code runs but gives a wrong answer on purpose.

fn find_orders_sql(customer: &str) -> String {
    format!("SELECT id FROM orders WHERE customer = '{customer}'")
}

fn main() {
    println!("{}", find_orders_sql("alice"));
    println!("{}", find_orders_sql("x' OR '1'='1"));
}
Output
SELECT id FROM orders WHERE customer = 'alice'
SELECT id FROM orders WHERE customer = 'x' OR '1'='1'
// The SQL text must be a &'static str: a literal in the program.
// A String made with format! at run time does not have this type.
struct Query {
    sql: &'static str,
    params: Vec<String>,
}

impl Query {
    fn new(sql: &'static str) -> Self {
        Query { sql, params: Vec::new() }
    }

    fn bind(mut self, value: &str) -> Self {
        self.params.push(value.to_string());
        self
    }
}

fn main() {
    let customer = "x' OR '1'='1";
    let query = Query::new("SELECT id FROM orders WHERE customer = ?1").bind(customer);
    println!("query: {}", query.sql);
    println!("args:  {:?}", query.params);
}
Output
query: SELECT id FROM orders WHERE customer = ?1
args:  ["x' OR '1'='1"]

This code does not compile, on purpose.

struct Query {
    sql: &'static str,
}

fn main() {
    let customer = String::from("alice");
    let text = format!("SELECT id FROM orders WHERE customer = '{customer}'");
    let query = Query { sql: &text };
    println!("{}", query.sql);
}
  • Verdict: library. The Rust standard library has no database API. The examples use only the standard library, and the bullets below describe the common crates.
  • format! builds SQL text from input in the same way as concatenation in other languages.
  • The type &'static str accepts a string literal and rejects a String made at run time, unless the program leaks the string on purpose. So the compiler stops SQL text that was built from input. The third example fails to compile for this reason. sqlx goes further: its query! macro takes a literal and checks it against the database at compile time.
  • With rusqlite, pass values in params! and use ?1, ?2 or :name in the text: conn.query_row("SELECT id FROM orders WHERE customer = ?1", params![customer], |row| row.get(0)).
  • With sqlx, chain .bind(value) for each placeholder: sqlx::query("SELECT id FROM orders WHERE customer = $1").bind(customer).
  • No example here uses a real database: rusqlite and sqlx were not in the local cargo cache when the examples were recorded, and the run has no network.

References

  1. CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection'), Description; Relationships; Common Consequences; Potential Mitigations
  2. OWASP Top 10:2025, A05:2025 Injection, Background; How to prevent
  3. 2025 CWE Top 25 Most Dangerous Software Weaknesses, the ranked list, rank 2
  4. rain.forest.puppy, NT Web Technology Vulnerabilities, Phrack Magazine 8(54), article 08, December 1998, the section on ODBC and MS SQL Server 6.5
  5. OWASP Cheat Sheet Series, SQL Injection Prevention Cheat Sheet, Primary Defenses, Options 1 to 4; Additional Defenses, Least Privilege
  6. PostgreSQL documentation, Frontend/Backend Protocol, Message Flow, Extended Query
  7. SQLite C interface, Binding Values To Prepared Statements, the description of parameters and the bind functions
  8. Go documentation, Avoiding SQL injection risk, the whole page
  9. The Python Standard Library, sqlite3, Python 3.14, How to use placeholders to bind values in SQL queries
  10. PostgreSQL security advisory, CVE-2006-2314, the description and the fixed releases
  11. Django documentation, Performing raw SQL queries, Passing parameters into raw()
  12. EF Core documentation, SQL Queries, Passing parameters; Dynamic SQL and parameters
  13. CodeQL query help, SQL query built from user-controlled sources (py/sql-injection), the query description
  14. Ruff rules, hardcoded-sql-expression (S608), What it does
  15. gosec, Go security checker, the list of rules, G201 and G202
  16. CVE-2023-34362, Progress MOVEit Transfer, the description and the publication date
  17. CVE-2021-27101, Accellion FTA, the description and the publication date
  18. CVE-2025-26794, Exim, the description and the publication date
  19. Information Commissioner's Office, TalkTalk cyber attack, how the ICO's investigation unfolded, the summary of the attack and the penalty

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/J1SS61/text.yaml