问题来源
在存储Scratch项目的xml内容时,DB报了个错:Incorrect string value: '\xF0\x9F\x91\x8B",...' for colum ...........(省略)
原因
因为数据库默认配置都是uft8,具体如下:
SHOW VARIABLES WHERE Variable_name LIKE 'character%' OR Variable_name LIKE 'collation%';
在MySQL中字符编码命名为uft8的实际上最大支持3个字节的字符,而uft8mb4才能最大支持4个字节的字符。
而数据库连接配置参数 characterEncoding 只有 UTF-8,并没有MySQL中 utf8mb4 对应的Java端配置可以配置。
解决办法
引用自:https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-reference-charsets.html
Notes
For Connector/J 8.0.12 and earlier: In order to use the
utf8mb4
character set for the connection, the server MUST be configured withcharacter_set_server=utf8mb4
; if that is not the case, whenUTF-8
is used forcharacterEncoding
in the connection string, it will map to the MySQL character set nameutf8
, which is an alias forutf8mb3
.For Connector/J 8.0.13 and later:
When
UTF-8
is used forcharacterEncoding
in the connection string, it maps to the MySQL character set nameutf8mb4
.If the connection option
connectionCollation
is also set alongsidecharacterEncoding
and is incompatible with it,characterEncoding
will be overridden with the encoding corresponding toconnectionCollation
.Because there is no Java-style character set name for
utfmb3
that you can use with the connection optioncharaterEncoding
, the only way to useutf8mb3
as your connection character set is to use autf8mb3
collation (for example,utf8_general_ci
) for the connection optionconnectionCollation
, which forces autf8mb3
character set to be used, as explained in the last bullet.
- 如果使用的Java驱动包版本为 Connector/J 8.0.12 以及更早期版本的话,那么就需要修改MySQL服务端的配置文件 my.cnf 或者 mysql.ini,设置
character_set_server=utf8mb4
,然后客户端使用 characterEncoding=utf8 来连接就可以解决问题了。 - 如果使用的Java驱动包版本为 Connector/J 8.0.13 以及更新版本的话,那么当客户端连接URL设置 characterEncoding=UTF-8 的时候,服务端会直接映射为utf8mb4。
注意
- 当连接参数 connectionCollation 和 characterEncoding 一同设置时,如果它们不兼容,那么 characterEncoding 会被 connectionCollation 中相符合的默认编码代替。
- 如果在8.0.13中使用三字节的utf8编码,那么只能利用 connectionCollation 来变相设置,例如设置为 utf8_general_ci。
- 别忘了库、表、字段中需要uft8mb4的地方也要同样设置好对应的字符编码。
- MySQL版本需要 5.5.3 以上。
顺便也需要注意下如下警告:
Warning
Do not issue the query SET NAMES with Connector/J, as the driver will not detect that the character set has been changed by the query, and will continue to use the character set configured when the connection was first set up.
参见:http://www.freeoa.net/osuport/db/emoji-char-write-in-mysql-using-utf8mb4_3095.html