MySQL数据库(七):数据导出与导入

一、数据导入
1.什么是导入:把系统文件的内容保存到数据库服务器的表里
2.导入数据时的注意事项?
-表中字段的个数要和文件列中的个数相等
-字段的类型要和文件中列的值匹配
3.导入数据命令格式:

load data infile '文件名' into table 表名  fields terminated by '分隔符' lines terminated by '\n';

*terminated by '分隔符':指定列的分隔符
*lines terminated by '\n':行的分隔符一般都是用'\n'(回车键)
3.例子:
1.1把系统用户信息保存到数据库服务器的usertab表里
㈠首先创建usertab表用来存放系统用户信息


create database db100;
create table db100.usertab(
username varchar(30),
password char(1),
uid samllint(2),
gid samllint(2),
comment varchar(50),
homedir varchar(60),
shell varchar(30),
index (username)
);

㈡将/etc/passwd文件导入到usertab表里

mysql> load data infile "/etc/passwd" into table db100.usertab fields terminated by ":" lines terminated by "\n";
Query OK, 25 rows affected (0.00 sec)
Records: 25  Deleted: 0  Skipped: 0  Warnings: 0

㈢查询是否导入成功
MySQL数据库(七):数据导出与导入

二、数据导出
1.什么是导出:把数据库表里的记录保存到系统文件里
吧mysql库下user表的所有记录保存到系统/tmp/user.txt文件里

2.导出的注意事项?
导出的内容有sql语句决定,若不指定路径,默认会放在执行导出命令时所在库对应的数据库目录下,应确保mysql用户对目标文件夹有写权限

3.导出数据命令格式:(不指定路径的话,默认文件保存在当前所在数据库的目录下)

select * from mysql.user into outfile '文件路径'

#指定列的分隔符

select user,host,password from mysql.user into outfile '文件名' fields terminated by "###";

#指定行的分隔符

select user,host,password from mysql.user into outfile '文件名' lines terminated by "!!!";

4.例子
导出mysql.user表到/tmp/user.txt

mysql> select * from mysql.user into outfile '/tmp/user.txt';
Query OK, 15 rows affected (0.00 sec)

MySQL数据库(七):数据导出与导入

把usertab表的所有记录都保存在/mydbdir/user.txt文件里
mysql> use db100;
Database changed
mysql> select * from usertab into outfile "/mydbdir/user.txt";
Query OK, 25 rows affected (0.00 sec)