導入和導出
導入和導出實際上都是對數據庫中的庫進行操作。導出是將數據庫導出以*.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