基本语法: load data [low_priority] [local] infile 'file_name txt' [replace | ignore] into table tbl_name [character set gbk] [fields [terminated by't'] [OPTIONALLY] enclosed by ''] [escaped by'\' ]]
[lines terminated by'n'] [ignore number lines] [(col_name, )]
1 load data infile 'csv文件路径\\test.csv'
2 replace into table 表名 3 fields terminated by ','
4 optionally enclosed by '"'
5 lines terminated by '\r\n'
6 ignore 1 lines(Id,@name,password);
说明:linux
第一行就是导入文件;数据库
第二行参看语法就会发现有两个词:replace 和 ignore 。replace和ignore关键词控制对现有的惟一键记录的重复的处理。若是你指定replace,新行将代替有相同的惟一键值的现有行。若是你指定ignore,跳过有惟一键的现有行的重复行的输入。若是你不指定任何一个选项,当找到重复键时,出现一个错误,而且文本文件的余下部分被忽略。windows
第三~四行很简单就是每一个具体字段内容之间是以逗号隔开的,那就以逗号分开。 erminated by描述字段的分隔符,默认状况下是tab字符(\t) 。enclosed by描述的是字段的括起字符,就是说字段中若是有引号,就当作是字段的一部分。 语法中还有一个是 escaped by, 它描述的是转义字符。默认的是反斜杠(backslash:\ )编码
第五行 lines terminated by是对每行进行分割,这里要注意一个问题,若是csv文件是在windows下生成,那分割用 ‘\r\n’,linux下用 ‘\n’。spa
第六行中 ignore 1 lines 是忽略第一行,由于第一行每每是字段名,后边括号中有个字段很特别 @name,它是说若是csv文件中有个字段我不想插进去,那就把对应字段名变成@name.3d
具体操做:code
step1.准备CSV文件blog
1.在数据库中建test数据表,表属性以下:it
2.csv文件的存储内容以下,命名为test1.csv,存储位置:“C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/test1.csv”:io
验证.csv编码格式是否正确,务必保证导入数据的编码格式是ANSI编码格式
step2.数据导入:
1.查询已有数据库:show databases;
2.使用这个数据库,使用命令:use flight_analysis;
3.查询咱们以前创建的表格test是否在test数据库中,使用命令:show tables;
4.导入数据库:
#导入数据中不包含中文
1 load data infile 'C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/test1.csv' --CSV文件存放路径 2 3 into test student--要将数据导入的表名 4 5 fields terminated by ',' optionally enclosed by '"' escaped by '"' 6 7 lines terminated by '\r\n';
#导入数据中包含中文
load data infile 'C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/test1.csv' --CSV文件存放路径 into table test character set gb2312 --要将数据导入的表名 fields terminated by ',' optionally enclosed by '"' escaped by '"' lines terminated by '\r\n';
1 #忽略第一行 2 load data infile "C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/datatest1.csv" 3 into table data_test 4 fields terminated by ',' optionally enclosed by '"' escaped by '"' 5 lines terminated by '\r\n' 6 ignore 1 lines;
1 select * from 表名 2 into outfile '导出路径\\test.csv' 3 fields terminated by ',' 4 optionally enclosed by '"' 5 escaped by '"' 6 lines terminated by '\n';