MySQL導入導出數據的中文亂碼問題


MySQL導入導出數據的中文亂碼問題

目錄

一、導出查詢結果到文件中

1、導出到CSV文件

2、導出到txt文件

3、導出到Excel文件

二、導入數據到表中

1、導入csv文件

2、導入txt文件

3、導入Excel文件


一、導出查詢結果到文件中

學生表

下面我們將學生表的查詢結果導出到文件中

1、導出到CSV文件

select * from student into outfile 'D:/Files/student.csv' fields terminated by ',' optionally enclosed by '"' escaped by '"' lines terminated by'\n';

此語句按一定格式在D:\Files\下生成了一個student.csv文件

2、導出到txt文件

select * from student into outfile 'D:/Files/student.txt';

產生的txt文件如下所示,這里采用的是默認格式,按tab分隔字段。當然這里也可以跟上面一樣,采用自定義個格式

3、導出到Excel文件

select * from student_grade into outfile 'D:/Files/student.xls';

此時,生成的Excel文件出現了亂碼問題

這是因為student表是采用utf8編碼(可以用show create table student;語句查看一下),而Excel文件則是GB2312編碼。

所以我們采用convert將中文字段轉換成gbk編碼:

select sid, convert((sname) using gbk) as sname, convert((gender) using gbk) as gender,class, convert((major) using gbk) as major from student into outfile 'D:\Files\student.xls';

這時就不會有亂碼問題了

二、導入數據到表中

接下來我們新建一個student2表,並且將剛才生成的幾個文件的數據導入到表中

1、導入csv文件

load data infile 'D:\\Files\\student.csv' into table student2 fields terminated by ',' optionally enclosed by '"' escaped by '"' lines terminated by'\n';

成功導入數據:

2、導入txt文件

刪除剛剛插入的所有數據:

再從txt文件中導入:

load data infile 'D:\\Files\\student.txt' into table student2;

成功導入數據:

3、導入Excel文件

刪除剛剛插入的所有數據:

再從Excel文件中導入:

load data infile 'D:\\Files\\student.xls' into table student2;

此時導入的數據出現亂碼:

我們在導入數據的時候指定編碼為gbk。

load data infile 'D:\\Files\\student.xls' into table student2 character set gbk; 

這樣就不會出現亂碼了:

 

轉自:https://www.cnblogs.com/conanwang/p/6118731.html


免責聲明!

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



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