CSV文件导入导出MySQL数据库

CSV文件导入导出MySQL数据库
1.导入

基本语法:
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);
说明:
第一行就是导入文件;
第二行参看语法就会发现有两个词:replace 和 ignore 。replace和ignore关键词控制对现有的唯一键记录的重复的处理。如果你指定replace,新行将代替有相同的唯一键值的现有行。如果你指定ignore,跳过有唯一键的现有行的重复行的输入。如果你不指定任何一个选项,当找到重复键时,出现一个错误,并且文本文件的余下部分被忽略。
第三~四行很简单就是每个具体字段内容之间是以逗号隔开的,那就以逗号分开。 erminated by描述字段的分隔符,默认情况下是tab字符(\t) 。enclosed by描述的是字段的括起字符,就是说字段中如果有引号,就当做是字段的一部分。 语法中还有一个是 escaped by, 它描述的是转义字符。默认的是反斜杠(backslash:\ )
第五行 lines terminated by是对每行进行分割,这里要注意一个问题,如果csv文件是在windows下生成,那分割用 ‘\r\n’,linux下用 ‘\n’。
第六行中 ignore 1 lines 是忽略第一行,因为第一行往往是字段名,后边括号中有个字段很特别 @name,它是说如果csv文件中有个字段我不想插进去,那就把对应字段名变成@name.
具体操作:
step1.准备CSV文件
1.在数据库中建test数据表,表属性如下:

2.csv文件的存储内容如下,命名为test1.csv,存储位置:“C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/test1.csv”:

验证.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';

posted @   冀未然  阅读(90)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示