Lesson 37: PreparedStatement & Preventing SQL Injection

07 Aug 2026 1 min Swarnil Singhai

PreparedStatement pre-compiles SQL with placeholders, so user input is always treated as data, never as executable SQL — this is how injection is stopped.

Real-time example

A login form that concatenates username into SQL directly can be broken with a crafted string; PreparedStatement makes that string harmless data.

// VULNERABLE - never do this:
String bad = "SELECT * FROM users WHERE name = '" + userInput + "'";

// SAFE:
PreparedStatement ps = conn.prepareStatement(
    "SELECT * FROM users WHERE name = ?");
ps.setString(1, userInput);
ResultSet rs = ps.executeQuery();

What's happening

Even if userInput contains SQL syntax, PreparedStatement binds it as a literal string value, not as SQL syntax — the query stays safe.

This single habit — always use ? placeholders — eliminates one of the most common real-world security vulnerabilities.

Advertisement