MySQL编码修改--> 支持emoji表情

来源:互联网 发布:淘宝助理5.5官方版 编辑:程序博客网 时间:2024/05/16 23:58

记线上服务的一次维护

线上服务一直跑的好好地,忽然今天客户说分享作品提示失败,自己去试了一下也能分享成功,只能去后台查早上七点多的日志记录。结果发现 果然后台报的有错

以下是报错信息截取的片段

org.springframework.jdbc.UncategorizedSQLException: ### Error updating database.  Cause: java.sql.SQLException: Incorrect string value: '\xF0\x9F\x98\x84' for column 'title' at row 1### The error may involve com.deepai.paipai.dao.PaipaiUserPictureMapper.insertSelective-Inline### The error occurred while setting parameters### SQL: insert into paipai_user_picture ( userId, createTime, url, surl, title, standby1, standby2, standby4, visibleType, hasReprinted )  values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )### Cause: java.sql.SQLException: Incorrect string value: '\xF0\x9F\x98\x84' for column 'title' at row 1; uncategorized SQLException for SQL []; SQL state [HY000]; error code [1366]; Incorrect string value: '\xF0\x9F\x98\x84' for column 'title' at row 1; nested exception is java.sql.SQLException: Incorrect string value: '\xF0\x9F\x98\x84' for column 'title' at row 1    at     ......省略n行Caused by: java.sql.SQLException: Incorrect string value: '\xF0\x9F\x98\x84' for column 'title' at row 1    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)    ......省略n行 org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:358)    ... 57 more

经过查资料也了解到 这是因为存储的信息包含了emoji表情(是4个字节的字符)而MySQL的utf8编码只支持3字节的数据。既然问题确定了,那就找对应的解决方案就好了。使用MySQL的 utf8mb4 编码即可。

以下是本次修改编码的记录,以作备忘并分享给大家。

  • 第一步(确认版本):
'确认   mysql -V >= 5.5.3   &&  MySQL驱动 >= 5.1.13   (这个是查资料看到的,有兴趣的朋友可以验证一下)'
  • 第二步(修改配置):
'vim /etc/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 init_connect='SET NAMES utf8mb4'
  • 第三步(查看配置是否生效,先重启mysqld服务):
SHOW VARIABLES WHERE Variable_name LIKE 'character_set_%' OR Variable_name LIKE 'collation%';   
'效果如下即可'

这里写图片描述

  • 第四步(修改已有数据库及表的编码):
ALTER DATABASE paipai360 CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;ALTER TABLE paipai_user_picture CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; 
  • 第五步(修改数据库连接配置):
'进行如下修改 去掉 characterEncoding=utf8 让它自己去匹配或者改为 utf8mb4 ''添加 autoReconnect=true '
jdbc.writeJdbcUrl = jdbc:mysql://xx.xx.xxx.xx:3306/paipai360?useUnicode=true&autoReconnect=true

然后重启应用 ok 齐活。

原创粉丝点击