导入和导出
导入和导出实际上都是对数据库中的库进行操作。导出是将数据库导出以*.sql结尾的SQL文件,导入是将*.SQL文件导入到数据库中。可以实现对数据库的备份,还原,更新。
导入数据库
创建一个SQL脚本文件,进行测试。
SQL脚本内容:
名称:test.sql
/*-----员工信息表-----*/
create database test;
use test;
create table staff
(
id int(10) primary key not null,
name char(4) not null,
sex enum('男','女') not null,
age tinyint(3) unsigned not null
);
insert into staff values(1,'张三','男',22);
insert into staff values(2,'李四','男',23);
insert into staff values(3,'王五','男',24);
导入数据库的两种方式:
注:导入数据库的文件,必须是以.sql文件结尾的文件
命令行导入命令:mysql -u 用户名 -p 密码 < SQL文件路径
mysql -uroot <test.sql
数据库导入命令:source SQL文件路径
mysql> source /root/test.sql
导入完成后,查看SQL文件是否导入成功
mysql> select *from test.staff;
+----+--------+-----+-----+
| id | name | sex | age |
+----+--------+-----+-----+
| 1 | 张三 | 男 | 22 |
| 2 | 李四 | 男 | 23 |
| 3 | 王五 | 男 | 24 |
+----+--------+-----+-----+
导出数据库
使用MySQL提供的mysqldump工具即可对数据库进行导出。
将test.sql文件删除,然后进行导出操作。
注:可以指定为任意文件类型的文件,如:txt,sql等等
rm -rf test.sql
mysqldump -uroot test > test2.sql
查看是否导出成功
ll test2.sql
-rw-r--r-- 1 root root 1948 5月 1 13:12 test2.sql
select导出文本报错
第一个报错信息
ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
过程及其解决
创建一个目录,用于存放select查询的数据
mkdir /select_txt
在MySQL数据库中使用select导出查询的数据
mysql> select * from test.staff into outfile '/select_txt/test.txt';
ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
命令解读:
select * from test.staff:查询test库中的staff表
into outfile ‘/select_txt/test.txt’:将查询结果输出到外部文件
然后就会遇见这个报错了,这是因为secure-file-priv项规定了导出的目录。
查看导出目录
mysql> show variables like '%secure%';
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| require_secure_transport | OFF |
| secure_file_priv | NULL |
+--------------------------+-------+
从查询结果上来看,其值为null,也就是没有定义导出目录。
secure_file_priv=NULL,表示不允许MySQL导入和导出。
secure_file_priv=目录,表示MySQL只能在某目录中执行导入和导出操作
secure_file_priv=,表示不限制MySQL的导入和导出,可以导入或导出到任何目录。
此项在/etc/my.cnf配置文件中设置,将secure_file_priv=添加到配置文件末尾,然后重启MySQL即可。
echo "secure_file_priv=" >> /etc/my.cnf
/etc/init.d/mysql.server restart
Shutting down MySQL.. SUCCESS!
Starting MySQL. SUCCESS!
接下来,继续进入到mysql中,执行select导出操作
select * from test.staff into outfile '/select_txt/test.txt';
ERROR 1 (HY000): Can't create/write to file '/select_txt/test.txt' (OS errno 13 - Permission denied)
第二个报错信息
ERROR 1 (HY000): Can’t create/write to file ‘/select_txt/test.txt’ (OS errno 13 - Permission denied)
这里显示创建文件权限拒绝,这是因为目录权限的问题,基于权限即可。
[root@linux ~]# chmod +777 /select_txt/
接下来在MySQL中执行select导出操作
mysql> select * from test.staff into outfile '/select_txt/test.txt';
执行成功后,查看文件是否被创建
[root@linux ~]# ll /select_txt/
总用量 4
-rw-rw-rw- 1 mysql mysql 48 5月 1 13:40 test.txt
查看文件内容
[root@linux ~]# cat /select_txt/test.txt
1 张三 男 22
2 李四 男 23
3 王五 男 24