引用csv文件导入MySQL

时间:2016-10-22 00:19:27

标签: mysql sql csv mysql-workbench

在Mac OSX上使用MySQL并使用MySQL Workbench执行SQL,这里是csv文件的SQL查询和内容,我想输入带引号的字符串,例如,我想输入f"o"o,我试过使用f\"o\"o,但似乎没有用,任何想法如何导入csv文件中的列的引用?

SQL查询

LOAD DATA LOCAL INFILE '/Users/foo/Downloads/import.csv' 
INTO TABLE tasks 
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

表架构

create database exercise;
CREATE TABLE IF NOT EXISTS tasks (
  task_id INT(11) NOT NULL AUTO_INCREMENT,
  subject VARCHAR(45) DEFAULT NULL,
  start_date DATE DEFAULT NULL,
  end_date DATE DEFAULT NULL,
  description VARCHAR(200) DEFAULT NULL,
  PRIMARY KEY (task_id)

CSV文件内容

1,"hello/world",,,"f\"o\"o"
2,"hello/world",,,"g\"o\"o"
3,"hello/world",,,"z\"o\"o"

导入后的内容

SELECT * FROM exercise.tasks;

enter image description here

修改1

尝试使用双引号来编码引用,尝试这种方式,导入后仍然与我发布的屏幕快照相同。

1,"hello/world",,,"f""o""o"
2,"hello/world",,,"g""o""o"
3,"hello/world",,,"z""o""o"

编辑2 ,尝试过此操作但无法正常工作(导入后,foo除了o o)

1,"hello/world",,,f'o'o
2,"hello/world",,,g'o'o
3,"hello/world",,,z'o'o

编辑3 ,尝试过此操作并且也无法正常工作(导入后,除了foo之外它是o o)

1,"hello/world",,,"f''o''o"
2,"hello/world",,,"g'o''o"
3,"hello/world",,,"z''o''o"

编辑4 ,警告我看到了,

LOAD DATA LOCAL INFILE '/Users/foo/Downloads/import.csv'  INTO TABLE tasks  FIELDS TERMINATED BY ','  ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\n'  3 row(s) affected, 6 warning(s): 1265 Data truncated for column 'start_date' at row 1 1265 Data truncated for column 'end_date' at row 1 1265 Data truncated for column 'start_date' at row 2 1265 Data truncated for column 'end_date' at row 2 1265 Data truncated for column 'start_date' at row 3 1265 Data truncated for column 'end_date' at row 3 Records: 3  Deleted: 0  Skipped: 0  Warnings: 6

的问候, 林

2 个答案:

答案 0 :(得分:1)

你应该加倍双引号来逃避它们:f""o""o

MySQL Doc

  

为了避免歧义,在一个中出现了ENCLOSED BY字符   字段值可以加倍并被解释为单个实例   这个角色。

答案 1 :(得分:1)

封闭的char加倍真的应该有效。也许有一个不同的问题导致您的导入失败?还要检查原始文本输出(Query -> Execute .. to Text)或命令行客户端。

或者,您可以使用不同的封闭字符。那么使用单引号呢?如果你的文本中没有逗号(即用作字段终止符的字符),则可以完全省略封闭字符(因为在这种情况下,字段终止符足以分隔条目)。