mysql问题-插入数据库中文乱码

一、数据库中文乱码情况

对于mysql数据库的乱码问题,有两种情况:

1. mysql数据库编码问题(建库时设定)。
2. 连接mysql数据库的url编码设置问题。

对于第一个问题,目前个人发现只能通过重新建库解决,建库的时候,选择UTF-8字符集。我试过修改现有数据库字符集为UFT-8,但是根本不起作用,插入的中文仍然乱码(中文显示成:???)。重建库时选择字符集为UTF-8之后,中文正常显示了。

补充:
第一个问题,可以单独的修改表的字符集,更可以单独的修改字段的字符集。 ALTER TABLE tbl_name DEFAULT CHARACTER SET character_name ALTER TABLE tbl_name CHANGE c_name c_name CHARACTER SET character_name

对于第二个问题,是这样的情况:我建库时设置了数据库默认字符集为UTF-8,通过mysql workbench直接插入中文显示完全正常。但是使用mybaits插入数据时,中文显示成了”???”这样的乱码。但从数据库获取的中文不会乱码。跟踪数据库操作,SQL语句中的中文还是显示正常的,但是插入到mysql数据库后就乱码了,于是判断可能是数据库连接的问题。后来在网上找了下资料,发现确实可以为mysql数据库的连接字符串设置编码方式,如下:

jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8

添加了useUnicode=true&characterEncoding=utf8参数之后,插入中文就正常了。

添加的作用是:指定字符的编码、解码格式。

例如:假设mysql数据库用的是GBK编码(也可能是其它,例如Ubuntu下就是latin1),而项目数据库用的是utf-8编码。这时候如果添加了useUnicode=true&characterEncoding=UTF-8 ,那么作用有如下两个方面:

1. 存数据时:

数据库在存放项目数据的时候会先用UTF-8格式将数据解码成字节码,然后再将解码后的字节码重新使用GBK编码存放到数据库中。

2.取数据时:

在从数据库中取数据的时候,数据库会先将数据库中的数据按GBK格式解码成字节码,然后再将解码后的字节码重新按UTF-8格式编码数据,最后再将数据返回给客户端。

注意:在xml配置文件中配置数据库utl时,要使用&的转义字符也就是&

  例如:<property name="url" value="jdbc:mysql://localhost:3306/email?useUnicode=true&amp;characterEncoding=UTF-8" />

二、HTML中常用的特殊字符:

1、最常用的字符实体(Character Entities)

显示结果 说明 Entity Name Entity Number
显示一个空格 &nbsp; &#160;
< 小于 &lt; &#60;
> 大于 &gt; &#62;
& &符号 &amp; &#38;
双引号 &quot; &#34;

2、其他常用的字符实体(Character Entities)

显示结果 说明 Entity Name Entity Number
© 版权 &copy; &#169;
® 注册商标 &reg; &#174;
× 乘号 &times; &#215;
÷ 除号 &divide; &#247;

三、mysql url连接属性

Properties and Descriptions
useUnicode

Should the driver use Unicode character encodings when handling strings? Should only be used when the driver can’t determine the character set mapping, or you are trying to ‘force’ the driver to use a character set that MySQL either doesn’t natively support (such as UTF-8), true/false, defaults to ‘true’

Default: true

Since version: 1.1g

characterEncoding

If ‘useUnicode’ is set to true, what character encoding should the driver use when dealing with strings? (defaults is to ‘autodetect’)

Since version: 1.1g


参考:
https://blog.csdn.net/zht666/article/details/8955952
https://blog.csdn.net/afgasdg/article/details/6941712
https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments