0

I got the date which is a string from a form. The date looks like xxxx-xx-xx xx:xx:xx

How can I save this date string to a column whose type is datetime in the database.

I use PreparedStatement psta = new PreparedStatement(sql) to set the values for the sql.

So for the Datetime type column, when i pre-set the value. I should use psta.setDate() or use psta.setString()?

Will
  • 633
  • 11
  • 26

2 Answers2

1

Please ignore all the comments and other answers that says to use setDate(). Instead, you have to use setTimestamp(), because your date string has time-of-day (hour, minute, second).

  1. First, you have to parse the text using SimpleDateFormat.
  2. Then convert from java.util.Date to java.sql.Timestamp.
  3. Finally call setTimestamp().

All in all, like this:

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date date = fmt.parse(dateString);
psta.setTimestamp(1, new java.sql.Timestamp(date.getTime()));
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • I use setTimestamp. But an error, java.sql.SQLException: Column count doesn't match value count at row 1, is thrown. I checked the number of my parameters and the name of parameters with the columns in the table. It is the same – Will Feb 22 '17 at 07:01
  • @Will You'd have to show more of your code for help with that, but that's a different question. This is the answer to this question. Create another question for problem matching up `setXxx()` calls with `?` markers in your SQL statement. – Andreas Feb 22 '17 at 07:12
  • @ Andreas Thank you so much, and i fixed the error. :) – Will Feb 22 '17 at 07:36
0
  1. Use SimpleDateFormat to convert your String to Date.

    ref: How to convert a String to a Date using SimpleDateFormat?

  2. Use psta.setDate() to set date for your sql query.

    ref : Using setDate in PreparedStatement

Community
  • 1
  • 1
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71