Abhash Upadhyaya
Abhash Upadhyaya

Reputation: 727

Prepared Statement binding of String to Date

Recently I stumbled upon a code where a parsed string from simple date format was used to bind in a prepared statement to a field of DATETIME type in MySql. How come it doesn't throw any error as ideally it should have been bind to a date type.

The field type is of DATETIME in MySql database.

ps.setString(index, stringDateObj);

Why setString works in this case? Shouldn't it have been ps.setDate(index, dateObj); ?

Upvotes: 2

Views: 461

Answers (1)

Jan
Jan

Reputation: 13858

Set String will work in all those cases where your Database has a conversion pattern for the string format. For formats not known to your database it will break.

You'll also have to deal differently with time zone in that case - that is, if your string format didn't include one.

If you can change the code, I recommend parsing in Java (where you know the format) and passing a java.sql.Date into PreparedStatement.

Upvotes: 2

Related Questions