环境:
- window10 x64专业版
- mysql8.0.21
- 以压缩包的方式安装mysql到window10中
参考:window下安装压缩版的mysql8
说明:
navicat中有两种导出数据的方法:“转储SQL文件”/导入导出向导,这里讲的内容对应navicat中的导入导出向导
一般我们导出数据使用转储sql的方法生成建表和insert语句就可以了。
一、导出数据
-- 准备表格数据
drop table if EXISTS test;
create table test(
id int primary key auto_increment,
name varchar(50),
age int,
score float,
birth datetime
);
insert into test(name,age,score,birth) values('小明',18,85.23,'1992-02-03'),('小花',20,100,'1992-12-03');
执行导出命令:
select * from test
where score>90
into OUTFILE 'e:/test/testoutput.txt'
FIELDS TERMINATED by ','
ENCLOSED by '"'
导出的结果如下:
注意:如果提示:
The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
,修改my.ini文件配置如下(参照:《将csv 文件存入mysql 报错The MySQL server is running…》)后重启mysql服务即可:
常用的导出语法:
<select statement> ::=
<table expression>
[ <into file clause> ]
<into file clause> ::=
into outfile '<file name>' <export option>
<export option> ::=
fields [ terminated by <alphanumeric literal> ]
[[ optionally ] enclosed by <alphanumeric literal>]
[ escaped by <alphanumeric literal> ]
lines terminated by <alphanumeric literal>
关键语法export option:
fields 后面表示导出时列的设置,如:【terminated by ‘,’ 表示列之间已“,”分割】;【ENCLOSED by ‘"’】表示所有列值都以双引号包裹,加上optionally后表示只有字符串的列才以双引号包裹;【escaped by ‘*’】表示使用*作为转义字符。
lines 后面表示行之间的设置,如:【lines terminated by ‘?’】表示每行之间使用"?"作为分割符。
二、导入数据
我们将上面导出的数据再导入到test表里(先将test表里数据清空):
-- 清空test表数据
truncate table test;
-- 导入testoutput.txt
load data infile 'e:/test/testoutput.txt'
replace
into table test
fields terminated by ','
ENCLOSED by '"';
select * from test;
导入后查询结果:
常用的导入语法:
<load statement> ::=
load data infile '<file name>'
[ replace | ignore ]
into table <table specification>
[ <fields specification> ]
[ <lines specification> ]
[ ignore <who number> lines ]
关键语法:
replace
和ignore
分别表示导入时如果表里面已经有这个记录的时候的处理方法,replace就表示替换,ignore就表示忽略不进行导入。如果什么都不写的话,系统遇到重复数据就直接报错。
ignore
表示导入时忽略前几行数据。