首页 > 代码库 > Mysql插入Emoji表情出错

Mysql插入Emoji表情出错

Caused by: java.sql.SQLException: Incorrect string value: \xF0\x9F\x98\x84 for column ‘NickName at row 1    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2734)    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)

UTF-8编码有可能是两个、三个、四个字节。Emoji表情是4个字节,而Mysql的utf8编码最多3个字节,所以数据插不进去。

解决方法:

1、修改mysql配置文件my.ini

找到配置文件是关键,可在window服务找到mysql的服务,右键属性查看,如图:

技术分享

打开配置文件,在响应的节点追加以下内容:

[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‘

2、修改数据库及表结构,命令行如下:

ALTER DATABASE ‘database’ CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;


ALTER TABLE ‘tablename‘ CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE ‘tablename‘ modify ‘columnName‘ text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

 

3、修改java程序中的数据库连接字符串,不要设置 characterEncoding,设置autoReconnect=true,连接串如下:

jdbc:mysql://127.0.0.1:3306/dbname?useUnicode=true&autoReconnect=true&allowMultiQueries=true

4、最后一步,重启mysql数据库,重启web服务器。

 

ok,搞定!

Mysql插入Emoji表情出错