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

posted @ 2021-01-24 22:49  逆袭小白  阅读(1589)  评论(0编辑  收藏  举报