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

本文介绍MySQL中数据导出与导入的方法,包括使用select...intooutfile导出数据到文件,以及使用loaddatalocalinfile从文件导入数据到表。同时,文章详细解释了--secure-file-priv参数对数据导入导出的影响及配置方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值