[英]How to insert a date from form to a column whose type is Datetime in database
I got the date which is a string from a form. 我从表单中得到了一个字符串日期。 The date looks like xxxx-xx-xx xx:xx:xx 日期看起来像xxxx-xx-xx xx:xx:xx
How can I save this date string to a column whose type is datetime in the database. 如何将该日期字符串保存到数据库中类型为datetime的列中。
I use PreparedStatement psta = new PreparedStatement(sql) to set the values for the sql. 我使用PreparedStatement psta = new PreparedStatement(sql)设置sql的值。
So for the Datetime type column, when i pre-set the value. 所以对于Datetime类型列,当我预设值时。 I should use psta.setDate() or use psta.setString()? 我应该使用psta.setDate()还是使用psta.setString()?
Please ignore all the comments and other answers that says to use setDate()
. 请忽略所有使用setDate()
的注释和其他答案。 Instead, you have to use setTimestamp()
, because your date string has time-of-day (hour, minute, second). 相反,您必须使用setTimestamp()
,因为您的日期字符串具有一天中的时间(小时,分钟,秒)。
SimpleDateFormat
. 首先,您必须使用SimpleDateFormat
解析文本。 java.util.Date
to java.sql.Timestamp
. 然后从java.util.Date
转换为java.sql.Timestamp
。 setTimestamp()
. 最后调用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()));
Use SimpleDateFormat to convert your String to Date. 使用SimpleDateFormat将您的字符串转换为日期。
ref: How to convert a String to a Date using SimpleDateFormat? 参考: 如何使用SimpleDateFormat将字符串转换为日期?
Use psta.setDate()
to set date for your sql query. 使用psta.setDate()
设置SQL查询的日期。
ref : Using setDate in PreparedStatement 参考: 在PreparedStatement中使用setDate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.