使用LOAD DATA +将文件导入mysql并获取全零

时间:2016-04-14 03:02:06

标签: mysql

我有以下文件(这只是我要导入的文件的一列。我想如果我将这1列正确,那么我可以执行其他列):

$ cat head_test_1col.csv
"Rec Open Date"
"2015-10-06"
"2015-10-06"
"2015-10-06"
"2015-10-06"
"2015-10-06"
"2015-10-06"
"2015-10-06"
"2015-10-06"
"2015-10-06"

现在我可以在mysql中创建我的表,如下所示:

CREATE TABLE IF NOT EXISTS test1234 (
id int(11) NOT NULL AUTO_INCREMENT COMMENT 'primary key',
`Rec Open Date` Date NOT NULL COMMENT 'Rec Open Date',
PRIMARY KEY (id)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=64 ;

然后我尝试使用以下任一项添加行,1或2,但它没有正确填充。

1

LOAD DATA LOCAL INFILE 'head_test_1col.csv' INTO TABLE test1234 COLUMNS TERMINATED BY ',';

2

LOAD DATA LOCAL INFILE 'head_test_1col.csv' INTO TABLE test1234

我得到以下内容(只是全部为零):

mysql> LOAD DATA LOCAL INFILE 'head_test_1col.csv' INTO TABLE test1234;
Query OK, 10 rows affected, 20 warnings (0.00 sec)
Records: 10  Deleted: 0  Skipped: 0  Warnings: 20

mysql>
mysql>
mysql> select * from test1234;
+----+---------------+
| id | Rec Open Date |
+----+---------------+
| 64 | 0000-00-00    |
| 65 | 0000-00-00    |
| 66 | 0000-00-00    |
| 67 | 0000-00-00    |
| 68 | 0000-00-00    |
| 69 | 0000-00-00    |
| 70 | 0000-00-00    |
| 71 | 0000-00-00    |
| 72 | 0000-00-00    |
| 73 | 0000-00-00    |
+----+---------------+
10 rows in set (0.00 sec)

mysql> 

有人可以建议我如何正确填充数据吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

LOAD DATA LOCAL INFILE 'head_test_1col.csv' INTO TABLE test1234 COLUMNS TERMINATED BY ',' 
ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES (`Rec Open Date`);

阐释:

ENCLOSED BY '"'             -- data is enclosed by "
LINES TERMINATED BY '\n'    -- define line termination
IGNORE 1 LINES              -- first line is column name, don't load as data
(`Rec Open Date`);          -- Only load for 2nd column, and 1st column is auto increased.

输出:

mysql> LOAD DATA LOCAL INFILE '/home/jinggang.sjg/data.csv' INTO TABLE test1234 COLUMNS TERMINATED BY ','
    -> ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES (`Rec Open Date`);
Query OK, 9 rows affected (0.00 sec)
Records: 9  Deleted: 0  Skipped: 0  Warnings: 0

mysql> select * from test1234;
+----+---------------+
| id | Rec Open Date |
+----+---------------+
| 64 | 2015-10-06    |
| 65 | 2015-10-06    |
| 66 | 2015-10-06    |
| 67 | 2015-10-06    |
| 68 | 2015-10-06    |
| 69 | 2015-10-06    |
| 70 | 2015-10-06    |
| 71 | 2015-10-06    |
| 72 | 2015-10-06    |
+----+---------------+
9 rows in set (0.00 sec)