1. 数据导入
使用load data infile语句加载数据
load data infile '/mysql_data/employee_name.csv' into table employee_names
fields terminated by ','
optionally enclosed by '"'
lines terminated by '\n';
文件名可以是一个完整的路径,指定其确切的位置。如果是相对目录,则会被解析于相对于客户机程序启动的目录。这里建议使用绝对路径。
如果文件开头有想要忽略的行,则可以使用ignore n lines指定忽略。如
load data infile '/mysql_data/employee_name.csv' into table employee_names
fields terminated by ','
optionally enclosed by '"'
lines terminated by '\n'
ignore 1 lines;
也可以用replace或ignore来处理重复的行,建议使用ignore。
load data infile '/mysql_data/employee_name.csv' replace into table employee_names
fields terminated by ','
optionally enclosed by '"'
lines terminated by '\n';
或
load data infile '/mysql_data/employee_name.csv' ignore into table employee_names
fields terminated by ','
optionally enclosed by '"'
lines terminated by '\n';
2. 数据导出
导出为文件
可以使用 select into outfile语句将输出结果保存到文件中。在导出的时候可以指定行列分隔符,方便再导入到其他数据平台。
select first_name,second_name into outfile 'employee_name.csv'
fields terminated by ','
optionally enclosed by '"'
lines terminated by '\n'
from employees
limit 10;
则数据将会被输出到{secure_file_priv}/{database_name}指定的路径中。如果文件已经存在,则数据导出会失败,所以每次执行或将文件移动到其他位置时都需要提供一个唯一的名称。
注:secure_file_priv的路径可以在配置文件my.cnf中查看。
可以将secure_file_priv值设置为「.」,这样数据导出就不会到相对路径下。导出的时候可以写一个绝对路径,则数据会被导出到该绝对路径下。
另存为表(可用于数据备份)
- 如果表不存在
create table first_name_only as
select distinct first_name
from employees;
- 如果表已经存在
insert into first_name_only
select distinct first_name
from employees;
当表中有PRIMARY KEY字段时,为了避免重复,可以使用insert ignore。
其实在实际工作中,我们很少用命令行来加载数据到数据库表中的。通常情况下是会使用一些可视化的客户端(如navicate)进行数据的导入。