← Back to Chapters

JDBC PreparedStatement

?️ JDBC PreparedStatement

? Quick Overview

The PreparedStatement interface is a sub-interface of Statement. It is used to execute parameterized queries. It is preferred over standard Statement for Insert, Update, and Delete operations because it provides better performance and prevents SQL Injection.

? Key Concepts

  • Parameterized Queries: Using ? as a placeholder for values.
  • executeUpdate(): The method used for INSERT, UPDATE, or DELETE (returns int).
  • Setters: Methods like setInt(), setString() to bind values.
  • SQL Injection: A security vulnerability that PreparedStatement prevents.

? Syntax & Theory

Instead of concatenating strings to build a query, we define the SQL structure first and pass values later.

? View Code Example
// Query with placeholders (?)
String query = "INSERT INTO students (name, city) VALUES (?, ?)";

// Create PreparedStatement
PreparedStatement pstmt = con.prepareStatement(query);

// Bind values to placeholders (Index starts at 1)
pstmt.setString(1, "John Doe");
pstmt.setString(2, "New York");

// Execute
int rowsAffected = pstmt.executeUpdate();

? Interactive Simulator: Parameter Binding

Enter data below and click "Execute" to see how Java binds values to the placeholders ? safely.

SQL: INSERT INTO students VALUES (?, ?)
Mock Database Table:
ID Name City
101 Amit Sharma Delhi

? Code Example — Inserting Data

? View Code Example
// Example: Inserting a new user into the database securely
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class InsertDemo {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/studentdb", "root", "root"
);

// The SQL query with placeholders
String q = "INSERT INTO students (name, city) VALUES (?, ?)";

// Get the PreparedStatement object
PreparedStatement pstmt = con.prepareStatement(q);

// Set values dynamically
pstmt.setString(1, "Alice Smith");
pstmt.setString(2, "London");

// Execute the query
int i = pstmt.executeUpdate();

if (i > 0) {
System.out.println("✅ Record inserted successfully.");
} else {
System.out.println("❌ Failed to insert record.");
}

con.close();

} catch (Exception e) {
e.printStackTrace();
}
}
}

? Live Output / Explanation

The program establishes a connection and inserts "Alice Smith" into the table. The executeUpdate() method returns the number of rows affected (1 in this case).

✅ Tips & Best Practices

  • Performance: The database pre-compiles the SQL, making repeated execution faster.
  • Security: Always use this for user input to stop hackers from manipulating your SQL queries.
  • Indexing: Remember that JDBC parameter indexes start at 1, not 0.

? Try It Yourself

  • Change the query to UPDATE students SET city = ? WHERE name = ?.
  • Create a Scanner to accept User Input from the console and pass it to the query.
  • Write a program to DELETE a record based on an ID.