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.
? as a placeholder for values.setInt(), setString() to bind values.Instead of concatenating strings to build a query, we define the SQL structure first and pass values later.
// 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();
Enter data below and click "Execute" to see how Java binds values to the placeholders ? safely.
| ID | Name | City |
|---|---|---|
| 101 | Amit Sharma | Delhi |
// 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();
}
}
}
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).
UPDATE students SET city = ? WHERE name = ?.DELETE a record based on an ID.