对MySQL UTF8 编码下生僻字符插入失败、假死问题的分析
一、问题:mysql 遇到某些中文插入异常
最近我发现了这样一个问题,问题如图1所示:
图1
如图1代码所示的语句在脚本中 load 入库的时候会 hang 住,web 前端、命令行操作则要么抛出
Incorrect string value: '\xF0\xA1\x8B\xBE\xE5\xA2...' for column 'name',
要么存入MYSQL数据库的内容会被截断或乱码,但是换做其它的中文则一切正常。
这看起来有些奇怪,按理说 utf8 编码是覆盖了所有中文的,就不应该出现上述问题。
二、原因:此 utf8 非彼 utf8
那我们先来看看插入异常的中文和正常的中文有啥区别,代码如图2所示:
图2
可以看到图2中插入异常的文字占了 4 个字节,而正常的则只占了 3 个字节。但是 utf8 字符编码不就是可变长,支持 1-4 字节的么?难道会和这个有关?
我们来看看官方文档就知道了:
10.1.10.6 The utf8mb4 Character Set (4-Byte UTF-8 Unicode Encoding)
The character set named utf8 uses a maximum of three bytes per character and contains only BMP characters. As of MySQL 5.5.3, the utf8mb4 character set uses a maximum of four bytes per character supports supplemental characters:For a BMP character, utf8 and utf8mb4 have identical storage characteristics: same code values, s