How to load date data using LOAD DATA in MySQL
P粉738046172
2023-08-22 22:12:49
<p>The default date format for a date column in MySQL is <code>YYYY-MM-DD HH:MM:SS</code>. </p>
<p>The data file I'm trying to load has a date field in the format of <code>DD-MON-YY HH:MM:SS</code>. When I load this file using the <code>LOAD DATA</code> command, the database gets confused and sets all date entries to <code>0000-00-00 00:00:00</code> or NULL . </p>
<p>This is my test using the <code>STR_TO_DATE</code> option but it doesn't work.</p>
<p><strong>测试文件(test_temp.csv)</strong></p>
<pre class="brush:php;toolbar:false;">c1, c2
07-JUN-12 22:50:19, "abc"
07-JUN-13 22:50:19, "bcd"</pre>
<p><strong>测试表(temp_test)</strong></p>
<pre class="brush:php;toolbar:false;">describe temp_test;
------- ------------- ------ ----- --------- -------
| Field | Type | Null | Key | Default | Extra |
------- ------------- ------ ----- --------- -------
| c1 | datetime | YES | | NULL | |
| c2 | varchar(10) | YES | | NULL | |
------- ------------- ------ ----- --------- ------- </pre>
<p><strong>数据加载命令:</strong></p>
<pre class="brush:php;toolbar:false;">load data
infile '/var/lib/mysql/DataSet-1/temp_test.csv'
ignore
into table temp_test
fields terminated by ','
enclosed by '"'
lines terminated by 'rn'
ignore 1 lines
(@var_c1,c2)
set c1 = STR_TO_DATE(@var_c1,'%d-%b-%y %h:%i:%s');</pre>
<p><strong>输出</strong></p>
<pre class="brush:php;toolbar:false;">Query OK, 2 rows affected, 2 warnings (0.00 sec)
Records: 2 Deleted: 0 Skipped: 0 Warnings: 0
MySQL> show warnings;
------- ------ -------------------------------------------------------------------------
| Level | Code | Message |
------- ------ -------------------------------------------------------------------------
| Error | 1411 | Incorrect datetime value: '07-JUN-12 22:50:19' for function str_to_date |
| Error | 1411 | Incorrect datetime value: '07-JUN-13 22:50:19' for function str_to_date |
------- ------ -------------------------------------------------------------------------
MySQL> select * from temp_test;
------ ------
| c1 | c2 |
------ ------
| NULL | abc |
| NULL | bcd |
------ ------ </pre>
<p>问题出在:</p>
<ol>
<li>输入日期列(应该是<code>07-JUN-12</code>还是<code>07-Jun-12</code>)或</li>
<li>我的格式字符串(<code>%d-%b-%y</code>)或</li>
<li>其他原因?</li>
</ol><p><br /></p>
Your
STR_TO_DATE()
format string is invalid. The hours in your sample data use the 24-hour clock (%H
or%k
), not the 12-hour clock (%h
). You can see all possible date format specifiers here.Will
change into
Your statement might look like this
After loading using your sample data