Java Academy Logo

Java Academy

JDBC PreparedStatement

PreparedStatement precompiles SQL with placeholders (?), making queries faster on repeated execution and immune to SQL injection when used correctly.

Basic PreparedStatement

String sql = "SELECT * FROM users WHERE email = ? AND active = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, userEmail);
ps.setBoolean(2, true);
ResultSet rs = ps.executeQuery();

Insert with PreparedStatement

String sql = "INSERT INTO orders (customer_id, total, created_at) VALUES (?, ?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setInt(1, customerId);
    ps.setBigDecimal(2, total);
    ps.setTimestamp(3, Timestamp.from(Instant.now()));
    ps.executeUpdate();
}

Advantages

  • Prevents SQL injection — parameters are escaped automatically.
  • Better performance — SQL is parsed once, executed many times.
  • Type-safe parameter binding with setInt, setString, setDate, etc.
  • Supports batch operations for bulk inserts.

Frequently Asked Questions

Are PreparedStatements always safe?

They prevent injection for parameter values. However, using string concatenation for table or column names (dynamic SQL structure) still requires careful validation.

Continue Learning