如何将文件中的时间戳数据上传到mysql中

时间:2010-06-19 10:18:42

标签: mysql load-data-infile

shell> cat /data/mysql/tm.sql
1276609796
1276606325

mysql> CREATE TABLE `tm_table` ( f TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP);
Query OK, 0 rows affected

mysql> LOAD DATA INFILE '/data/mysql/tm.sql' INTO TABLE tm_table;
Query OK, 2 rows affected
Records: 2  Deleted: 0  Skipped: 0  Warnings: 2

mysql> SHOW WARNINGS;
+---------+------+----------------------------------------+
| Level   | Code | Message                                |
+---------+------+----------------------------------------+
| Warning | 1265 | Data truncated for column 'f' at row 1 |
| Warning | 1265 | Data truncated for column 'f' at row 2 |
+---------+------+----------------------------------------+
2 rows in set

mysql> SELECT f FROM tm_table;
+---------------------+
| f                   |
+---------------------+
| 0000-00-00 00:00:00 |
| 0000-00-00 00:00:00 |
+---------------------+
2 rows in set

我更喜欢以时间戳格式保留日期。 如何将文件中的时间戳数据上传到mysql?

2 个答案:

答案 0 :(得分:4)

找到解决方案。感谢the_void的想法。

mysql> LOAD DATA INFILE '/data/mysql/tm.sql' INTO TABLE tm_table
    -> (@var1) SET f=FROM_UNIXTIME(@var1);
Query OK, 2 rows affected
Records: 2  Deleted: 0  Skipped: 0  Warnings: 0

mysql> select f from tm_table;
+---------------------+
| f                   |
+---------------------+
| 2010-06-15 16:52:05 |
| 2010-06-15 17:49:56 |
+---------------------+
2 rows in set

答案 1 :(得分:0)

您应该使用FROM_UNIXTIME功能,如下所示:

#!/bin/bash

FILENAME=$1
TEMP=temp.txt

for LINE in $(cat $FILENAME); do
    echo "INSERT INTO tm_table(f) VALUES(FROM_UNIXTIME(`echo $LINE | tr -d '\r\n'`));" >> $TEMP
done

mysql -u XXX --password=XXX < $TEMP

rm $TEMP