MySQL记录select到文件、从文件导入

注:本文简单总结,详细内容请参考官方文档

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

猜你喜欢

转载自blog.csdn.net/huangzhilin2015/article/details/100216602