Query parameterization helps keep your database safe by stopping bad code from sneaking in. It makes sure user inputs are treated as data, not commands.
Query parameterization for safety in Node.js
const sql = 'SELECT * FROM users WHERE id = ?'; const params = [userId]; db.query(sql, params, (err, results) => { if (err) throw err; console.log(results); });
Use placeholders like ? or named parameters depending on your database library.
Pass user inputs as separate parameters, not inside the query string.
const sql = 'SELECT * FROM products WHERE category = ? AND price < ?'; const params = ['books', 20]; db.query(sql, params, callback);
const sql = 'INSERT INTO users (name, email) VALUES (?, ?)';
const params = [userName, userEmail];
db.query(sql, params, callback);const sql = 'UPDATE orders SET status = ? WHERE order_id = ?'; const params = ['shipped', orderId]; db.query(sql, params, callback);
This program safely fetches user data by id using query parameterization. It prevents harmful input from changing the query.
import mysql from 'mysql2'; const db = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'shop' }); const userId = 5; // Imagine this comes from user input const sql = 'SELECT * FROM users WHERE id = ?'; const params = [userId]; db.query(sql, params, (err, results) => { if (err) { console.error('Database error:', err); return; } console.log('User data:', results); });
Never build SQL queries by joining strings with user input directly.
Most database libraries support parameterized queries; check your library's docs.
Parameterization also helps with performance by allowing query caching.
Query parameterization keeps your database safe from injection attacks.
Always pass user inputs as separate parameters, not inside query strings.
Use your database library's parameter syntax to write safe queries.
Practice
Solution
Step 1: Understand SQL injection risk
When user input is directly included in query strings, attackers can inject harmful SQL code.Step 2: Role of parameterization
Parameterization sends user input separately, so the database treats it only as data, not code.Final Answer:
It prevents SQL injection by separating user input from the query structure. -> Option AQuick Check:
Query parameterization = prevents SQL injection [OK]
- Thinking parameterization speeds up queries automatically
- Believing it removes all syntax rules
- Confusing parameterization with encryption
Solution
Step 1: Identify parameter placeholder syntax
The 'mysql2' library uses '?' as placeholders for parameters.Step 2: Check correct parameter passing
Parameters must be passed as an array as the second argument to 'query'.Final Answer:
connection.query('SELECT * FROM users WHERE id = ?', [userId]); -> Option DQuick Check:
mysql2 uses '?' + array for parameters [OK]
- Concatenating variables directly into query strings
- Using template literals inside query strings
- Using incorrect placeholder syntax like $userId
const { Client } = require('pg');
const client = new Client();
await client.connect();
const userId = "1; DROP TABLE users;";
const res = await client.query('SELECT * FROM users WHERE id = $1', [userId]);
console.log(res.rows.length);Solution
Step 1: Understand parameterization effect
The query uses parameterized input with '$1', so the input is treated as data, not code.Step 2: Analyze input impact
The string "1; DROP TABLE users;" is searched as a literal id, which likely matches no rows.Final Answer:
It will return the number of rows with id exactly matching "1; DROP TABLE users;". -> Option AQuick Check:
Parameterized queries treat input as data, not commands [OK]
- Assuming injection will run despite parameterization
- Expecting syntax errors from malicious input
- Thinking all rows will be returned without a WHERE clause
db.run('INSERT INTO users (name, age) VALUES (?, ?)', name, age, (err) => {
if (err) throw err;
console.log('User added');
});Solution
Step 1: Check parameter passing syntax
sqlite3 expects parameters as an array or object, not separate arguments.Step 2: Correct usage
Parameters should be passed as an array: [name, age].Final Answer:
Parameters should be passed as an array, not separate arguments. -> Option BQuick Check:
sqlite3 parameters = array [OK]
- Passing parameters as separate arguments
- Confusing named and positional parameters
- Ignoring callback error handling
Solution
Step 1: Understand batch insertion with parameterization
To insert multiple records safely, use placeholders for each value and pass all values as an array.Step 2: Avoid unsafe concatenation or unparameterized queries
Concatenating strings or using template literals risks injection; separate queries without parameters are inefficient and unsafe.Final Answer:
Use a parameterized query with multiple placeholders and pass all values in an array. -> Option CQuick Check:
Batch insert = parameterized placeholders + values array [OK]
- Concatenating user data into query strings
- Running unparameterized queries repeatedly
- Using template literals for SQL queries
Ready to prove it?
Pass the test and this pattern moves unknown
