將MySQL查詢結果導出到Excel

總結將mysql的查詢結果導出到文件的方法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-mysqllinux

設置查詢結果自動寫入到指定文件

-- 設置
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等工具導出啦,在服務端經過命令行導出並傳到本地。sql

法一:使用into outfile命令,遇到下面狀況,放棄shell

-- 提示下面錯誤
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命令this

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

參考:.net

相關文章
相關標籤/搜索