🧩 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 |
|
|
|---|---|---|
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)
SQL query is precompiled by the database.
?placeholders are bound to values at runtime.The database executes the query using the compiled plan — faster and safer.
🔢 Setting Parameter Values
Method | Use Case |
|---|---|
| For integers |
| For strings |
| For floating-point numbers |
| 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,SELECTqueriesExecuting 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
PreparedStatementafter use withstmt.close();Always use placeholders (
?) for valuesUse try-catch-finally or try-with-resources to manage exceptions and cleanups