Security

SQL Injection Code Examples

Real SQL injection vulnerabilities with working exploit examples — in Python, JavaScript, Java, and TypeScript. For each language: the vulnerable code, how an attacker exploits it, and the correct parameterized fix.

OWASP Top 10 #3 — affects every language with database access.


What is SQL injection?

SQL injection (SQLi) occurs when user-controlled input is embedded directly into a SQL query without sanitization. The attacker injects SQL syntax that changes the query's logic — bypassing authentication, extracting data, modifying records, or in some databases, executing OS commands.

Impact

Full database read, authentication bypass, data deletion, server takeover (via xp_cmdshell)

Frequency

Consistently in OWASP Top 10 since 2010. #1 cause of reported data breaches worldwide

Detection

Hard to spot in code review — looks like normal string formatting to human reviewers

Jump to language:

PythonJavaScriptJavaTypeScript
Python

Python SQL Injection

❌ Vulnerable

username = request.form['username']

# Attacker sends: ' OR '1'='1' --
query = "SELECT * FROM users WHERE username = '" + username + "'"
cursor.execute(query)
# → SELECT * FROM users WHERE username = '' OR '1'='1' --'
# → Returns ALL rows — authentication bypassed

✅ Secure Fix

username = request.form['username']

# Parameterized query — driver escapes all input
cursor.execute(
    "SELECT * FROM users WHERE username = %s",
    (username,)  # Tuple, even for single value
)

# SQLAlchemy (recommended for larger apps):
user = db.session.query(User).filter_by(username=username).first()

Full guide: SQL Injection in Python →

JavaScript

Node.js SQL Injection

❌ Vulnerable (Node.js + mysql2)

const username = req.body.username;

// Template literal in SQL = injection risk
const query = `SELECT * FROM users WHERE username = '${username}'`;
connection.query(query, (err, results) => {
  // Attacker sends: ' UNION SELECT table_name,null FROM information_schema.tables --
  // → Exposes all table names in the database
});

✅ Secure Fix

const username = req.body.username;

// Use ? placeholders — mysql2 escapes all values
connection.query(
  "SELECT * FROM users WHERE username = ?",
  [username],
  (err, results) => { /* safe */ }
);

// With async/await + prepared statements:
const [rows] = await connection.execute(
  "SELECT * FROM users WHERE username = ?",
  [username]
);

Full guide: SQL Injection in JavaScript →

Java

Java SQL Injection (JDBC)

❌ Vulnerable

String username = request.getParameter("username");
String password = request.getParameter("password");

// String concatenation — classic SQLi vector
String sql = "SELECT * FROM users WHERE username = '" + username
           + "' AND password = '" + password + "'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);

✅ Secure Fix — PreparedStatement

String username = request.getParameter("username");
String password = request.getParameter("password");

// PreparedStatement with ? placeholders
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);  // position 1 = first ?
pstmt.setString(2, password);  // position 2 = second ?
ResultSet rs = pstmt.executeQuery();
// Input is always treated as data, never as SQL

Full guide: SQL Injection in Java →

TypeScript

TypeScript SQL Injection

❌ Vulnerable (Prisma raw query)

// Prisma $queryRawUnsafe — dangerous with user input
const username = req.body.username as string;

const users = await prisma.$queryRawUnsafe(
  `SELECT * FROM User WHERE username = '${username}'`
  // ← Never use template literals in $queryRawUnsafe
);

✅ Secure Fix

// Option 1: Prisma ORM (best — no raw SQL needed)
const user = await prisma.user.findFirst({
  where: { username: req.body.username }
});

// Option 2: $queryRaw with Prisma.sql template tag (parameterized)
import { Prisma } from '@prisma/client';
const users = await prisma.$queryRaw(
  Prisma.sql`SELECT * FROM User WHERE username = ${req.body.username}`
  // ↑ Prisma.sql automatically parameterizes this
);

Full guide: SQL Injection in TypeScript →


🛡️
The universal rule across all languages: Never build SQL queries by concatenating or interpolating user input. Always use your database driver's parameterized query mechanism — the placeholder syntax differs (%s, ?, $1) but the principle is identical.

Detect SQL injection in your code automatically

Paste any database query code — LearnCodeGuide finds SQLi vulnerabilities across all languages instantly.

Scan for SQL Injection →

Per-Language Guides

Python SQL InjectionJavaScript SQL InjectionJava SQL InjectionTypeScript SQL InjectionPython Security MistakesJavaScript XSS

Published by LearnCodeGuide Team · Last reviewed: October 2025