mysql insert日期格式,MySQL - 如何在INSERT语句中解析字符串值为DATETIME格式?

I have a MySQL database, with a column that is date type DATETIME.

I am getting a string value for a date / time from an external application. That string value looks like this:

'5/15/2012 8:06:26 AM'

MySQL throws an error on the INSERT: "Error. Incorrect datetime value". My workaround was to change the column type to VARCHAR, which works, but I really need the data as a proper Date & Time for future use.

I researched accepted formatting for MySQL DATETIME values, and found that MySQL wants the DATETIME format as 'YYYY-MM-DD HH:MM:SS'.

I can't change the external application to reformat the date / time string in a format, so my only chance is to deal with it.

What I need to do, I think, is parse the existing string, using MySQL syntax, inside of my INSERT statement, but I'm not sure how to do that. I have some idea that I need to use a SELECT clause, perhaps STR_TO_DATE, somehow in combination with my INSERT statement.

Here is my current INSERT statement. I removed the other fields that are not causing a problem, just to make the example clean.

INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES ('5/15/2012 8:06:26')

Thank you for any help, I am a SQL newbie.

解决方案

Use MySQL's STR_TO_DATE() function to parse the string that you're attempting to insert:

INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES

(STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值