linux 用shell脚本执行sql语句并将查询结果保存到文件中[解决报错问题]

一、编写脚本

#!/bin/bash
Host=localhost
User=root
Password=root

mysql -h $Host -u$User -p$Password << EOF
use Library;
select email from User where Id = "123456" into outfile '/tmp/fd.txt';
EOF

二、MySQL的配置

1、当你写好shell时以为运行一下脚本就能导出结果时,有可能会出现

The MySQL server is running with the – secure-file-priv option so it cannot execute this statement
这个错误因为没有配置好MySQL的导出文件的设置
登录进mysql,输入 show variables like ‘%secure%’;
linux 用shell脚本执行sql语句并将查询结果保存到文件中[解决报错问题]_第1张图片
我这里设置的路径是 /
当secure_file_priv的值为null ,表示限制mysqld 不允许导入|导出

当secure_file_priv的值为/tmp/ ,表示限制mysqld 的导入|导出只能发生在/tmp/目录下

当secure_file_priv的值没有具体值时,表示不对mysqld 的导入|导出做限制

如果时Linux的话 找到/etc/mysql/my.cnf文件
在[mysqld] 下添加 secure_file_priv="/"
在这里插入图片描述

2、然后可能出现 Can’t create/write to file xxxx (Errcode: 13 - Permission denied)错误

进入mysql输入 show variables like ‘%dir%’; 命令
linux 用shell脚本执行sql语句并将查询结果保存到文件中[解决报错问题]_第2张图片
在最后一行tmpdir 后边的值是 /tmp ,只要你把保存结果的文件放到这个文件夹就行了

你可能感兴趣的:(Linux)