我正在解析具有以下数据结构的xml文件:
<row Id="253858" UserId="40883" Name="Scholar" Date="2009-03-08T01:52:32.570" />
<row Id="253860" UserId="19483" Name="Supporter" Date="2009-03-08T01:57:31.733" />
<row Id="253861" UserId="74951" Name="Autobiographer" Date="2009-03-08T02:02:32.390" />
我使用ruby脚本来解析这些数据并将它们插入到mysql数据库中。以下是我的数据表的样子:
+---------+-------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+-------------------+-----------------------------+
| id | int(11) | NO | PRI | NULL | |
| user_id | int(11) | NO | | NULL | |
| name | varchar(40) | YES | | NULL | |
| created | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+---------+-------------+------+-----+-------------------+-----------------------------+
此xml文件包含大量记录,直到解析器到达第3条记录,我才会收到任何错误,所有数据都会正确解析并插入表中:
| 253857 | 23658 | Critic | 2009-03-08 01:52:32 |
| 253858 | 40883 | Scholar | 2009-03-08 01:52:33 |
| 253860 | 19483 | Supporter | 2009-03-08 01:57:32 |
+--------+---------+--------------------+---------------------+
但是当我们使用row Id="253861"
访问记录时,我收到以下mysql错误:
load.rb:21:in `execute': Incorrect datetime value: '2009-03-08T02:02:32.390' for column 'created' at row 1 (Mysql::Error)
from load.rb:21:in `on_start_element'
from load.rb:133:in `parse'
from load.rb:133:in `<main>'
如果您需要插入记录的ruby方法:
def on_start_element(element, attributes)
if element == 'row'
@st.execute(attributes['Id'], attributes['UserId'], attributes['Name'], attributes['Date'])
end
end
end
我不认为这与脚本有关,因为我从xml文件中提取了记录并尝试直接插入到我的mysql表中,我收到以下错误:
mysql> insert into badge values(253861,74951,'Autobiographer','2009-03-08T02:02:32.390');
ERROR 1292 (22007): Incorrect datetime value: '2009-03-08T02:02:32.390' for column 'created' at row 1
我还尝试在xml文件中插入上述记录之后的记录,我得到了相同的结果:
mysql> insert into badge values(253862,49628,'Teacher','2009-03-08T02:12:30.807');
ERROR 1292 (22007): Incorrect datetime value: '2009-03-08T02:12:30.807' for column 'created' at row 1
因此日期字符串中的某些内容会使mysql不满意。我无法弄清楚的是,具有相同日期结构的日期和以前的记录没有任何问题。希望我已经用信息解释了问题。
答案 0 :(得分:5)
既然你说你在几个地方插入日期,我建议你写一个帮助方法进行日期转换,你可以在任何需要插入日期的地方重复使用
require 'date'
def iso8601_to_mysql_datetime(date)
DateTime.parse(date).to_time.strftime("%F %T")
end
iso8601_to_mysql_datetime('2009-03-08T02:02:32.390')
=> "2009-03-08 02:02:32"
注意:上面将ISO8601
转换为MySQL理解的字符串
MySQL日期和时间文字文档可以在这里找到:
http://dev.mysql.com/doc/refman/5.6/en/date-and-time-literals.html