DEV Community

丁久
丁久

Posted on • Originally published at dingjiu1989-hue.github.io

SQL Injection Prevention Guide

This article was originally published on AI Study Room. For the full version with working code examples and related articles, visit the original post.

SQL Injection Prevention Guide

SQL Injection Prevention Guide

SQL Injection Prevention Guide

SQL Injection Prevention Guide

SQL Injection Prevention Guide

SQL Injection Prevention Guide

SQL Injection Prevention Guide

SQL Injection Prevention Guide

SQL Injection Prevention Guide

SQL Injection Prevention Guide

Understanding SQL Injection

SQL injection is a code injection technique where an attacker inserts malicious SQL statements into application queries. It has been the top vulnerability in the OWASP Top 10 for years and remains one of the most damaging attack vectors despite being well-understood.

How It Works

Consider a vulnerable login query built by string concatenation:

String query = "SELECT * FROM users WHERE email = '" + email + "' AND password = '" + password + "'";

An attacker providing email = admin@example.com' -- comments out the password check, logging in as admin without knowing the password. Worse, providing email = '; DROP TABLE users; -- could destroy the database entirely.

Defense Layer 1: Parameterized Queries

Parameterized queries (also called prepared statements) separate SQL logic from data. User input is always treated as data, never as executable code.

Node.js (mysql2)

const mysql = require('mysql2/promise');

const connection = await mysql.createConnection({ /* config */ });

const [rows] = await connection.execute(

'SELECT * FROM users WHERE email = ? AND password_hash = ?',

[email, passwordHash]

);

Python (psycopg2)

import psycopg2

conn = psycopg2.connect("dbname=test user=postgres")

cur = conn.cursor()

cur.execute(

"SELECT * FROM users WHERE email = %s AND status = %s",

(user_email, 'active')

)

Java (JDBC)

String sql = "SELECT * FROM products WHERE category = ? AND price < ?";

PreparedStatement stmt = connection.prepareStatement(sql);

stmt.setString(1, category);

stmt.setBigDecimal(2, maxPrice);

ResultSet rs = stmt.executeQuery();

Go (database/sql)

rows, err := db.Query(

"SELECT * FROM users WHERE email = $1 AND active = $2",

email, true,

)

Defense Layer 2: ORM Protections

Modern ORMs provide built-in protection against SQL injection when used correctly.


Read the full article on AI Study Room for complete code examples, comparison tables, and related resources.

Found this useful? Check out more developer guides and tool comparisons on AI Study Room.

Top comments (0)