MySql5.7.14存储表情字符报错Incorrect string value

在用mysql存储微信用户的昵称时,报了如下错误:

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x98\x84' for column

经过网络搜索,总结原因为
因为表情符在某些终端,比如ios5.0以上,是以四字节表示的,而传统的utf8只能保存3字节,所以报错了。

解决办法:修改mysql字符集为utf8mb4
解决步骤:
第一步:修改数据库字符集
第二步:升级最新数据库驱动

  • 1.1修改数据库字符集:
alter database databasename CHARACTER SET utf8mb4;
  • 1.2修改表字符集:
alter tbale tablename CHARACTER SET utf8mb4;
  • 1.3修改mysql的init文件
[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
init_connect='SET NAMES utf8mb4'

然后,重启mysql。

经过以上修改,使用以下语句:


SHOW VARIABLES WHERE Variable_name 
LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%';

查看数据库的字符集都为utf8mb4了。

  • 2.在升级最新的mysql数据库驱动(mysql-connector-java 6.0.3)后出现了新错误:
com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: 
The server time zone value '?й???????' is unrecognized or represents more than one time zone. 
You must configure either the server or JDBC driver 
(via the serverTimezone configuration property) 
to use a more specifc time zone value if you want to utilize time zone support.

原因有三个:
- 2.1 新driverClassName的路径改为com.mysql.cj.jdbc.Driver了
- 2.2 数据库连接url上添加 serverTimezone=GMT
- 2.3 数据库连接url上添加 userSSL=false

至此,所有的问题全部解决。

参考:

http://blog.csdn.net/wwtang9527/article/details/40947469
http://blog.csdn.net/sinat_33201781/article/details/51830688

你可能感兴趣的:(MySql)