將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

參考:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM