mysql 查詢導出(txt,csv,xls)

1 簡介

  工作中產品經常會臨時找我導出一些數據,導出mysql查詢結果數據有幾種方法,下面介紹3種.

   ①  mysql -u  -p  -e "sql" db > filepath  

   ②  echo "sql" | login > filepath

   ③  mysql login; use db; select * into outfile "filepath" from tb condition;

 

2 實例講解

  ①  mysql -uroot -p123456 -e "select * from tb_user where id = 1" testdb > ~/wbwcachedata/tb_user.txt

      mysql -uroot -p123456 -e "select * from tb_user where id = 1" testdb > ~/wbwcachedata/tb_user.csv

      mysql -uroot -p123456 -e "select * from tb_user where id = 1" testdb > ~/wbwcachedata/tb_user.xls

    

    個人比較喜歡導出爲csv,因爲xls經常會出現幾個字段合到了一列的情況.導出csv之後,以製表符tab爲分隔點即可轉成excel.

    另外如果出現中文亂碼,可直接用命令轉碼  iconv -futf8 -tgb2312 -otb_user.xls tb_user1.xls.或者直接用文件軟件轉碼即可(excel轉ANSI碼).

 

    ②  echo "select * from tb_user where id = 1" | mysql  -uroot  -p123456 > ~/wbwcachedata/mysqlexport0327-01.csv

      錯誤提示: ERROR 1046 (3D000) at line 1: No database selected

      沒關係,我們在sql中加上use db即可:   

        echo "use testdb;  select * from tb_user where id = 1;" | mysql  -uroot  -p123456 > ~/wbwcachedata/mysqlexport0327-01.csv

     ③   登錄mysql

      mysql -uroot -p 

      執行sql

      select * into outfile '~/wbwcachedata/mysqlexport0327-02.csv' from tb_user where id = 1;

      錯誤提示:  ERROR 1046 (3D000): No database selected

      記得選擇數據庫

      use  testdb;

      select * into outfile '~/wbwcachedata/mysqlexport0327-02.csv' from tb_user where id = 1;

      錯誤提示:  ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

      此時有兩種解決辦法,第一種是改mysql的my.ini的secure-file-priv路徑重啓mysql.

      第二種是

      執行   show variables like '%secure%';

      返回

                        +--------------------------+-----------------------+
                         | Variable_name            | Value                 |
                        +--------------------------+-----------------------+
                         | require_secure_transport | OFF                   |
                         | secure_auth              | ON                    |
                         | secure_file_priv         | /var/lib/mysql-files/ |
                        +--------------------------+-----------------------+

      發現mysql允許導出路徑爲/var/lib/mysql-files/

      我們執行sql

      select * into outfile '/var/lib/mysql-files/mysqlexport0327-02.csv' from tb_user where id = 1;

      然後用cp/mv命令把該文件轉移到我們想要的路徑.

      一般我是選第二種,在沒必要的情況下,不應主動修改my.ini.

 


      

    

 

 

   

   

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章