将MySQL查询结果导出到Excel

总结将mysql的查询结果导出到文件的方法

总结

使用命令

select user, host, password from mysql.user into outfile '/tmp/user.xls';

-- 执行上述命令会提示下面的错误
ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

-- 解决1,查看下面这个变量指示的路径,把文件导出到该路径下即可
SHOW VARIABLES LIKE "secure_file_priv";

select user, host, password from mysql.user into outfile '/var/lib/mysql-files/user.xls';

参考:https://stackoverflow.com/questions/32737478/how-should-i-tackle-secure-file-priv-in-mysql

设置查询结果自动写入到指定文件

-- 设置
pager cat > /tmp/test.txt 

-- 验证,执行如下查询控制台不显示,查询结果在/tmp/test.txt文件中
select user, host, password from mysql.user;

-- 取消设置
pager

shell执行mysql命令将结果重定向到文件

# 写法一:
mysql -D mysql -e "select host, user, password from user" > /tmp/user.xls;

# 定法二:如果sql过长,可以这样写
mysql -h localhost -uroot -p123456 < t.sql  > /tmp/result.txt  

# t.sql可以这样写
use mysql;  
select host, user, password from user; 

# 写法三:
mysql -h localhost -uroot -p123456 -e "source t.sql" > /tmp/result.txt  

应用举例

需要执行一个复杂的sql,并将结果导出成excel格式,不能外网联结固不能用navicat等工具导出啦,在服务端通过命令行导出并传到本地。

法一:使用into outfile命令,遇到下面情况,放弃

-- 提示下面错误
ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
-- 查看下面变量是NULL
SHOW VARIABLES LIKE "secure_file_priv";

法二:使用paper命令,导出的格式不方便转成excel,放弃

法三:使用mysql命令

mysql -h xxx.com -uroot -p'password' -e "
复杂的查询SQL
" > result-utf8.xls

# 还有最重要的一步,在linux中默认是utf-8格式,需要转成gbk格式
iconv -futf8 -tgb2312 -oresult-gbk.xls result-utf8.xls

参考:

posted @ 2018-10-07 16:31  okokabcd  阅读(12276)  评论(1编辑  收藏  举报