SQLExceptioncom.mysql.jdbc.SQLError in createSQLException Incorrect string value: '\xF0\x9F\x99\x8F'

一、问题

mysql报错:

SQLExceptioncom.mysql.jdbc.SQLError in createSQLException Incorrect string value: '\xF0\x9F\x99\x8F' for column 'content' at row 1

{conn-10041, pstmt-25440} execute error. insert into emails( `id`, `sender`, `receiver`, `subject`, `content`, `type`, `status`, `emailsvc`, `ctime`, `utime`, `ver`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

Incorrect string value: '\xF0\x9F\x99\x8F' for column 'content' at row 1

二、原因解析

我们可以看到错误提示中的字符xF0\x9F\x99\x8F ,这对应UTF-8编码格式中的4字节编码(UTF-8编码规范)。

正常的汉字一般不会超过3个字节,为什么为出现4个字节呢?实际上是它对应的是智能手机输入法中的表情。

那为什么会报错呢?因为MySQL中的utf-8并不是真正意义上的utf-8,它只能存储1~3个字节长度的utf-8编码,如果想存储4个字节的必须用utf8mb4类型。

不过要使用utf8mb4类型,首先要保证Mysql版本要不低于 MySQL 5.5.3。

三、解决方案

(1) 删除表情字符


(2) 使用utf8mb4数据类型


要用这种策略,如果MySql版本低于5.5.3,首先要进行版本升级,然后将对应的数据类型改为utf8mb4类型。
如果使用的是Connector/J 连接数据库,需要在配置中把编码格式改为utf8mb4(set character_set_server=utf8mb4 in the connection config)。


(3 )自定义过滤规则,将文本中出现的四字节UTF-8字符过滤或转化为自定义类型。

preg_replace_callback(
        '/./u',
        function (array $match) {
            return strlen($match[0]) >= 4 ? '' : $match[0];
        },
        $str);

————————————————
版权声明:本文为CSDN博主「仰望星空的脚踏实地」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43145299/article/details/85048381

发布了173 篇原创文章 · 获赞 326 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/William0318/article/details/104038151