PreparedStatement Setter Methods for Different Data Types
Fast recall
Quick revision
Core answer
Whether you know the typed setters and how to bind NULL and dates correctly.
Using setString for numbers/dates, or passing Java null instead of setNull.
Use setBigDecimal for money and setTimestamp for datetimes; setNull for NULLs.
Interview-ready guide
Interview answer
For example, INSERT INTO payment(customer_id, amount, paid_at, note) VALUES (?,?,?,?) can use setLong(1,id), setBigDecimal(2,amount), setObject(3,paidAt), and setNull(4,Types.VARCHAR). Passing null to a primitive setter is impossible, and blindly using setObject for every value can produce driver-specific type inference.
PreparedStatement Setter Methods for Different Data Types
Direct Answer
PreparedStatement setter methods bind Java values to one-based parameter positions. Use a setter that matches the intended SQL/JDBC type, such as setString, setInt, setLong, setBigDecimal, setDate, setTimestamp, setObject, or setNull. Binding keeps values separate from SQL syntax; it does not require every driver/database to literally compile the statement before values arrive.
Code Example
String sql = "INSERT INTO orders (id, amount, note, created_at, coupon) " +
"VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement ps = con.prepareStatement(sql)) {
ps.setLong(1, 1001L);
ps.setBigDecimal(2, new java.math.BigDecimal("199.99")); // money
ps.setString(3, "gift wrap");
ps.setTimestamp(4, new java.sql.Timestamp(System.currentTimeMillis()));
ps.setNull(5, java.sql.Types.VARCHAR); // explicit NULL
ps.executeUpdate();
}
Common Mistakes & Pitfalls
setStringfor numbers/dates: causes type mismatches or string-stored values.doublefor money: usesetBigDecimalto avoid rounding errors.- Bare Java
null: prefersetNull(idx, Types.X)so the driver knows the type. setDatewhen you need time: usesetTimestampto keep the time component.
Check your understanding
Answer these without looking back at the article.
- What is PreparedStatement in JDBC and why is it preferred?
- How do you use PreparedStatement for an INSERT query in JDBC?
- How does PreparedStatement prevent SQL injection?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.