MySql csv文件導入導出


一、導出到csv(本地導出)

通過mysql客戶端shell連接到服務器,選擇使用的數據庫,輸入sql代碼: 

select * from test_info   

into outfile '/tmp/test.csv'   

fields terminated by ','    ------字段間以,號分隔

optionally enclosed by '"'  ------字段用"號括起

escaped by '"'         ------字段中使用的轉義符為"

lines terminated by '\r\n';  ------行以\r\n結束

上面的 導出文件夾 需要手動創建,否則會報錯:ERROR 1 (HY000): Can't create/write to file '\tmp\DKX.csv' (Errcode: 2)

select * from test_info into outfile '/tmp/test.csv' fields terminated by ',' optionally enclosed by '"' escaped by '"' lines terminated by '\r\n';

 

 注意:

  where gscode = 'BS監控'  有中文,導不出數據

  解決方法:

    where gscode like 'BS%'

  

 

  

二、csv文件導入

load data infile '/tmp/test.csv'   

into table test_info    

fields terminated by ','  

optionally enclosed by '"' 

escaped by '"'   

lines terminated by '\r\n'; 

 

#insert

load data infile '/tmp/test.csv' into table test_info fields terminated by ',' optionally enclosed by '"' escaped by '"' lines terminated by '\r\n';

#replace

load data infile '/tmp/test.csv' repalce into table test_info fields terminated by ',' optionally enclosed by '"' escaped by '"' lines terminated by '\r\n';

場景:表1中的數據需要導入表2(表1、2結構相同,都有自增id字段)。表1中的自增id字段不要導出,讓其在數據導入表2時自動生成,避免可能出現重復的自增id。

  導出:

    

 

  導入:

    

 

    注意:

      如果是遠程連接的數據庫,導出、導入時可能報錯:ERROR 1045 (28000): Access denied for user 'quantuser'@'%' (using password: YES)

      

 

      

    解決方法:

      導出:(-N 不導出標題行)

      mysql -h host -u user --password=pwd dbname  -N -e "select * from table" > D:/tmp/test.csv

      

 

      導入:

      登錄,連接上數據庫之后

      用 load data local  infile 'XXX.csv' (如果指定LOCAL關鍵詞,從客戶主機讀文件。如果LOCAL沒指定,文件必須位於服務器上。(LOCAL在MySQL3.22.6或以后版本中可用。))

      

 

三、把從mongodb 中導出的csv文件,導入到 mysql

  導出:

    

  

  導入mysql:

    

 

效果:

  

  

  注意:

    導入、導出的兩個mysql 的數據庫屬性要一致,否則導入數據之后,中文字段是亂碼的。

    

 


免責聲明!

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



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