手机端插入Emoji表情,保存到数据库时报错:
Caused by: java.sql.SQLException: Incorrect string value: '\xF0\x9F\x98\x84' for column 'review' 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个字节,所以数据插不进去。
解决方案:将Mysql的编码从utf8转换成utf8mb4。
1. 修改my.ini [mysqld] character-set-server=utf8mb4
2. 在Connector/J的连接参数中,不要加characterEncoding参数。 不加这个参数时,默认值就时autodetect。
3. 将已经建好的表也转换成utf8mb4
命令:ALTER TABLE `TABLE_NAME` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; (将TABLE_NAME替换成你的表名)
4. 将需要使用emoji的字段设置类型为:
命令:ALTER TABLE `TABLE_NAME`MODIFY COLUMN `COLUMN_NAME` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
参考:
http://stackoverflow.com/questions/2108824/mysql-incorrect-string-value-error-when-save-unicode-string-in-django
http://dev.mysql.com/doc/refman/5.5/en/connector-j-reference-charsets.html
转自:http://www.w2bc.com/Article/8533