- 微信nickname乱码及mysql编码格式设置(utf8mb4)
-
今天在写微信公众平台项目时,写到一个用户管理模块,接口神马的已经调试好了,于是将用户从微信服务器保存到本地数据库,发现报错:
java.sql.SQLException: Incorrect string value: '\xF0\x9F\x92\x94' for column 'nickname' at row 1
大致说的是保存nickname字段时,发现不正确的字符串值,于是在保存前,将用户的昵称打印了出来,发现有emoji表情,上网查了一下,utf-8大小可能有三种分别为2字节、3字节、4字节,而Mysql中的utf-8编码格式最多支持3字节,所以需要升级Mysql版本及编码格式:
Luckily, MySQL 5.5.3 (released in early 2010) introduced a new encoding called utf8mb4 which maps to proper UTF-8 and thus fully supports Unicode, including astral symbols.
也就是mysql在5.5.3版本中引入新的编码格式,取名为utf8mb4,所以如果你电脑上的版本低于此版本,请先更新电脑中的Mysql版本,查看Mysql版本:
mysql -V
mysql Ver 14.14 Distrib 5.6.23, for osx10.9 (x86_64) using EditLine wrapper发现电脑中的版本没问题,于是直接找改编码格式的方法:
Make sure to set the client and server character set as well. I have the following in my MySQL configuration file (/etc/my.cnf):
于是去查找my.cnf文件所在的方位,在我电脑中路径为(用homebrew安装的)
/usr/local/Cellar/mysql/5.6.23/my.cnf
用sudo vim打开该文件:
$ sudo vim my.cnf
添加编码格式配置:
[client]
default-character-set = utf8mb4 [mysql]
default-character-set = utf8mb4 [mysqld]
character-set-client-handshake = FALSE
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci重启mysql服务,查看编码格式
mysql> SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%';
+--------------------------+--------------------+
| Variable_name | Value |
+--------------------------+--------------------+
| character_set_client | utf8mb4 |
| character_set_connection | utf8mb4 |
| character_set_database | utf8mb4 |
| character_set_filesystem | binary |
| character_set_results | utf8mb4 |
| character_set_server | utf8mb4 |
| character_set_system | utf8 |
| collation_connection | utf8mb4_unicode_ci |
| collation_database | utf8mb4_unicode_ci |
| collation_server | utf8mb4_unicode_ci |
+--------------------------+--------------------+
10 rows in set (0.00 sec)发现已经设置成功,于是重新启动程序,发现还是报错,错误还是刚才的错误,这下可以确定问题不在数据库的编码格式中了,于是继续找答案,发现jdbc驱动有问题,当前程序中的驱动版本:
mysql-connector-java-5.1.7-bin.jar
于是去mysql官网找最新jdbc驱动,地址:
http://dev.mysql.com/downloads/file.php?id=456317
版本:
mysql-connector-java-5.1.35-bin.jar
心想这下应该可以了吧,重新启动程序,我靠! 发现还报错,继续是刚才的错误,这下只能找找hibernate配置文件中是否有问题了,hibernate配置文件中的连接地址为:
jdbc:mysql:///wechat_development?useUnicode=true&characterEncoding=utf8
上*中找了找解决方案,里面也没说为何,直接说把后面的useUnicode及characterEncoding直接去掉就好了,于是配置文件变成如下:
jdbc:mysql:///wechat_development