PreparedStatement for INSERT in JDBC
Fast recall
Quick revision
Core answer
Whether you can write a parameterized INSERT correctly.
Off-by-one on 1-based parameter indexes, or using executeQuery for an INSERT.
Note parameter indices are 1-based and executeUpdate returns the affected-row count.
Interview-ready guide
Interview answer
For example, INSERT INTO customer(name,email) VALUES (?,?) is prepared once, then setString(1,name) and setString(2,email) bind data safely. executeUpdate() should report one affected row for a normal single-row insert. To read an identity value, prepare with Statement.RETURN_GENERATED_KEYS and inspect getGeneratedKeys after success.
PreparedStatement for INSERT in JDBC
Direct Answer
Create a PreparedStatement with fixed INSERT SQL and ? placeholders, bind each value using one-based indexes, then call executeUpdate. The returned count normally reports affected rows, though driver/database behavior for special statements and success-without-count values should be respected. Use a transaction when the insert belongs to a larger atomic operation.
Code Example
String sql = "INSERT INTO users (name, email, age) VALUES (?, ?, ?)";
try (PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, "Ravi"); // index 1 (1-based!)
ps.setString(2, "ravi@x.com"); // index 2
ps.setInt(3, 29); // index 3
int rows = ps.executeUpdate(); // INSERT -> executeUpdate -> row count
System.out.println(rows + " row inserted");
}
Common Mistakes & Pitfalls
- 0-based indexing: the first
?is index 1, not 0. executeQueryfor INSERT: useexecuteUpdate(returns row count).- Wrong setter for the type:
setStringfor a number column can fail or mis-store. - Not closing: wrap in try-with-resources.
Check your understanding
Answer these without looking back at the article.
- Are PreparedStatement parameter indices 0-based or 1-based?
- What does executeUpdate return for an INSERT?
- How do you insert multiple rows efficiently?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.