Language-Specific Implementations
Language-Specific Implementations
Each programming language offers different approaches to parameterized queries. Python developers using various database libraries:
# psycopg2 for PostgreSQL
import psycopg2
conn = psycopg2.connect("dbname=test user=postgres")
cur = conn.cursor()
# Named parameters
cur.execute(
"INSERT INTO logs (user_id, action, timestamp) VALUES (%(user_id)s, %(action)s, %(timestamp)s)",
{'user_id': user_id, 'action': 'login', 'timestamp': datetime.now()}
)
# Positional parameters
cur.execute(
"SELECT * FROM products WHERE price BETWEEN %s AND %s ORDER BY price",
(min_price, max_price)
)
# Using psycopg2's SQL composition for dynamic queries
from psycopg2 import sql
table_name = sql.Identifier('user_data_2023')
query = sql.SQL("SELECT {fields} FROM {table} WHERE active = %s").format(
fields=sql.SQL(',').join([sql.Identifier(f) for f in field_list]),
table=table_name
)
cur.execute(query, (True,))
Node.js implementations across different database drivers:
// MySQL2 with promise-based API
const mysql = require('mysql2/promise');
async function secureQueries() {
const connection = await mysql.createConnection({host: 'localhost', user: 'root', database: 'test'});
// Simple parameterized query
const [rows] = await connection.execute(
'SELECT * FROM users WHERE created_at > ? AND status = ?',
[startDate, 'active']
);
// Multiple inserts with parameterization
const users = [
['John', '[email protected]', 25],
['Jane', '[email protected]', 30],
["Robert'; DROP TABLE users; --", '[email protected]', 0] // Safe!
];
const insertStmt = await connection.prepare('INSERT INTO users (name, email, age) VALUES (?, ?, ?)');
for (const user of users) {
await insertStmt.execute(user);
}
await insertStmt.close();
}
// PostgreSQL with pg library
const { Pool } = require('pg');
const pool = new Pool();
async function postgresExample() {
// Numbered placeholders
const result = await pool.query(
'SELECT * FROM orders WHERE user_id = $1 AND total > $2',
[userId, minimumTotal]
);
// Using PREPARE for repeated queries
await pool.query('PREPARE user_orders AS SELECT * FROM orders WHERE user_id = $1');
const preparedResult = await pool.query('EXECUTE user_orders ($1)', [userId]);
}