0Pricing
Java Academy · Lesson

PreparedStatement

Safe parameterized queries.

Why PreparedStatement?

Building SQL by concatenating user input is dangerous and slow.

PreparedStatement solves both problems:

  • Safety — values are sent separately from the SQL, preventing SQL injection.
  • Performance — the database can parse and plan the query once, then reuse it.

The SQL Injection Problem

Consider building a query with string concatenation. If a user types '; DROP TABLE users; -- as their name, the concatenated SQL executes that as a command.

This is SQL injection, one of the oldest and most damaging web vulnerabilities. PreparedStatement makes it impossible by design.

public class Main {
    public static void main(String[] args) {
        String userInput = "'; DROP TABLE users; --";
        // Dangerous: never do this
        String unsafe = "SELECT * FROM users WHERE name = '" + userInput + "'";
        System.out.println("Injected SQL becomes:");
        System.out.println(unsafe);
    }
}

All lessons in this course

  1. JDBC Fundamentals
  2. PreparedStatement
  3. Transactions
  4. Connection Pooling with HikariCP
← Back to Java Academy