将CSV导入mySQL

时间:2017-01-12 16:56:43

标签: mysql csv

我有一个CSV文件,其中包含一个可以包含以逗号分隔的值列表的列。

我使用以下SQL语句导入数据:

LOAD DATA LOCAL INFILE 'C:/tmp/geography.csv' 
INTO TABLE geography 
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
IGNORE 1 ROWS;

但是,当它到达包含逗号分隔的值列表的行时,它会中断导入。

数据格式如下:

id,zip,location_type,primary_city,state,county,area_codes
  ,00501,UNIQUE,Holtsville,NY,Suffolk County,631
  ,00601,STANDARD,Adjuntas,PR,Adjuntas Municipio,"787,939"

enter image description here

1 个答案:

答案 0 :(得分:0)

我无法重现这个问题。

档案:/path/to/file/geography.csv

id,zip,location_type,primary_city,state,county,area_codes
\N,00501,UNIQUE,Holtsville,NY,Suffolk County,631
\N,00601,STANDARD,Adjuntas,PR,Adjuntas Municipio,"787,939"
\N,00602,STANDARD,Aguada,PR,Aguada Municipio,"797,949"

MySQL命令行:

mysql> SELECT VERSION();
+-------------------------+
| VERSION()               |
+-------------------------+
| 5.7.16-0ubuntu0.16.04.1 |
+-------------------------+
1 row in set (0.00 sec)

mysql> DROP TABLE IF EXISTS `geography`;
Query OK, 0 rows affected (0.01 sec)

mysql> CREATE TABLE IF NOT EXISTS `geography` (
    ->   `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    ->   `zip` VARCHAR(5) NOT NULL,
    ->   `location_type` VARCHAR(25) NOT NULL,
    ->   `primary_city` VARCHAR(25) NOT NULL,
    ->   `state` VARCHAR(25) NOT NULL,
    ->   `county` VARCHAR(25) NOT NULL,
    ->   `area_codes` VARCHAR(25) NOT NULL
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> LOAD DATA LOCAL INFILE '/path/to/file/geography.csv'
    -> INTO TABLE `geography`
    -> FIELDS TERMINATED BY ',' ENCLOSED BY '"'
    -> IGNORE 1 ROWS;
Query OK, 3 rows affected (0.00 sec)
Records: 3  Deleted: 0  Skipped: 0  Warnings: 0

mysql> SELECT
    ->   `id`,
    ->   `zip`,
    ->   `location_type`,
    ->   `primary_city`,
    ->   `state`,
    ->   `county`,
    ->   `area_codes`
    -> FROM
    ->   `geography`;
+----+-------+---------------+--------------+-------+--------------------+------------+
| id | zip   | location_type | primary_city | state | county             | area_codes |
+----+-------+---------------+--------------+-------+--------------------+------------+
|  1 | 00501 | UNIQUE        | Holtsville   | NY    | Suffolk County     | 631        |
|  2 | 00601 | STANDARD      | Adjuntas     | PR    | Adjuntas Municipio | 787,939    |
|  3 | 00602 | STANDARD      | Aguada       | PR    | Aguada Municipio   | 797,949    |
+----+-------+---------------+--------------+-------+--------------------+------------+
3 rows in set (0.00 sec)