注:本文簡單總結,詳細內容請參考官方文檔
1、select到文件
select [fields] from [tableName] [join] where [options] into outfile [file];
例:
select * from test_table where 1=1 into outfile 'D://backup.sql';
也可以設置編碼:
select * from test_table where 1=1 into outfile 'D://backup.sql' character set utf8mb4;
2、從文件導入
load data local infile [file] into table [tableName];
例:
load data local infile 'D://backup.sql' into table test_table;
和select一樣,也可以指定編碼:
load data local infile 'D://backup.sql' into table test_table character set utf8mb4;
3、異常
可能會出現以下異常:
The MySQL server is running with the --secure-file-priv option so it cannot execute this statement.
解釋:
在該版本MySQL下,--secure-file-priv(global)參數用於限制數據的導入導出操作,比如上述提到的load data 、select ... into outfile語句(還有LOAD_FILE),該參數有三個可配置值:
- NULL:不允許導入導出操作
- 空(''):導入導出操作沒有任何限制
- 目錄名:導入導出操作被限制在指定的目錄(該目錄必須存在,MySQL不會自動創建該目錄)
該參數的默認值要看具體平臺,我們可以show一下查看該參數的當前配置:
show global variables like 'secure_file_priv';
並且該參數是隻讀的,不能直接使用set進行配置:
mysql> set global secure_file_priv='';
1238 - Variable 'secure_file_priv' is a read only variable
mysql>
解決:
找到my.ini(或my.cnf),手動在[mysqld]中配置該參數:
--secure-file-priv=''
然後重啓MySQL即可.
參考文檔:https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_secure_file_priv