JAVA - Zero to Hero / JDBC - Java Database Connectivity

PreparedStatements

🧩 What is PreparedStatement in JDBC? (Easy + Technical)

A PreparedStatement is a special type of SQL query object in JDBC that lets you write queries with placeholders (?) instead of directly putting values in the SQL.

✅ Why Use It?

  • You can set values later using methods like .setInt() or .setString() before running the query.

  • It helps prevent SQL injection (a common hacking technique).

  • It is faster when you run the same query multiple times with different values.


💥 What is SQL Injection?

SQL Injection is a security vulnerability where an attacker can insert malicious SQL code into your application's database query — usually through input fields.


✅ Why Use PreparedStatement Instead of Statement?

Feature

Statement

PreparedStatement

Security

❌ Prone to SQL Injection

✅ Prevents SQL Injection

Performance

❌ Parses every time

✅ Compiled once, reused

Parameter Binding

❌ Manual string concatenation

✅ Uses placeholders (?)

Code Readability

❌ Messy

✅ Clean and readable


🔐 SQL Injection Safe

When you use regular Statement, malicious input can break or manipulate your query.

Statement stmt = con.createStatement();
stmt.execute("DELETE FROM users WHERE username = '" + userInput + "'");

With PreparedStatement, this is safe:

PreparedStatement stmt = con.prepareStatement("DELETE FROM users WHERE username = ?");
stmt.setString(1, userInput);

🧪 How It Works (Internally)

  1. SQL query is precompiled by the database.

  2. ? placeholders are bound to values at runtime.

  3. The database executes the query using the compiled plan — faster and safer.


🔢 Setting Parameter Values

Method

Use Case

setInt(index, intValue)

For integers

setString(index, stringValue)

For strings

setDouble(index, doubleValue)

For floating-point numbers

setDate(index, dateValue)

For SQL Date objects

🧾 Example:

PreparedStatement stmt = con.prepareStatement("INSERT INTO users (id, name) VALUES (?, ?)");
stmt.setInt(1, 101);               // First parameter is ID
stmt.setString(2, "Likitha");      // Second parameter is name
stmt.executeUpdate();

📌 Typical Use Cases

  • INSERT, UPDATE, DELETE, SELECT queries

  • Executing same query multiple times with different values

  • Preventing SQL injection

  • Working with form inputs, user data, or batch processing


🚫 Don’t Forget:

  • Always close your PreparedStatement after use with stmt.close();

  • Always use placeholders (?) for values

  • Use try-catch-finally or try-with-resources to manage exceptions and cleanups