Parameterized Query SQL Injection Prevention
Contrast string-interpolated SQL with parameterized statements, allowing safe dynamic ORDER BY through whitelisting.
Code
-- 危险示范:拼接用户输入(永远不要这样做)
-- SELECT * FROM products WHERE name = '克" OR "1"="1'
-- ORDER BY 攻击同理:排序字段直接内插
-- 安全形态:值全部走绑定参数
SELECT id, name, price_cents
FROM products
WHERE category = $1
AND price_cents BETWEEN $2 AND $3
ORDER BY price_cents
LIMIT $4;
-- 绑定:$1='electronics', $2=1000, $3=5000, $4=20
-- IN 列表的动态占位符:结构生成、值绑定
SELECT id, name
FROM products
WHERE id IN ($1, $2, $3);
-- 占位符数量由应用层数组长度生成,值逐个绑定
-- ORDER BY 无法参数化:白名单映射是唯一出路
-- 应用层伪代码:
-- allowed = { 'price': 'price_cents',
-- 'name': 'name',
-- 'created': 'created_at DESC' }
-- order_sql = allowed[user_input] or fail()
SELECT id, name, price_cents
FROM products
WHERE category = $1
ORDER BY price_cents DESC NULLS LAST; -- order_sql 来自白名单
-- 标识符必须动态时用格式化函数加引号
SELECT quote_ident('user_input_column'); -- 带引号的安全标识符How the snippet works
The file runs SELECT statements, touching products.
Mechanically, the statements are built from: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.
Applying it
Run the statement against the products table; the LIMIT keeps the probe cheap while you tune the predicates.
Statements that matter
SELECT id, name, price_cents
FROM products
WHERE category = $1
AND price_cents BETWEEN $2 AND $3
ORDER BY price_cents
LIMIT $4;
SELECT id, name
FROM products
WHERE id IN ($1, $2, $3);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
FAQ
- Which objects does the SQL touch?
- `products`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.