MySQL中如何存储字符宽度最大为4个字节的UTF-8编码?

本文介绍了在MySQL中遇到无法存储4字节UTF-8字符(如表情符号)的问题及其原因,即MySQL的utf8字符集仅支持3字节字符。解决方案涉及调整数据库配置为utf8mb4,特别是对于Connector/J的不同版本,需要采用不同的连接参数。同时,需要注意数据库、表和字段的字符集设置,确保与连接设置一致。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题来源

在存储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 with character_set_server=utf8mb4; if that is not the case, when UTF-8 is used for characterEncoding in the connection string, it will map to the MySQL character set name utf8, which is an alias for utf8mb3.

For Connector/J 8.0.13 and later:

  • When UTF-8 is used for characterEncoding in the connection string, it maps to the MySQL character set name utf8mb4.

  • If the connection option connectionCollation is also set alongside characterEncoding and is incompatible with it, characterEncoding will be overridden with the encoding corresponding to connectionCollation.

  • Because there is no Java-style character set name for utfmb3 that you can use with the connection option charaterEncoding, the only way to use utf8mb3 as your connection character set is to use a utf8mb3 collation (for example, utf8_general_ci) for the connection option connectionCollation, which forces a utf8mb3 character set to be used, as explained in the last bullet.

  1. 如果使用的Java驱动包版本为 Connector/J 8.0.12 以及更早期版本的话,那么就需要修改MySQL服务端的配置文件 my.cnf 或者 mysql.ini,设置 character_set_server=utf8mb4,然后客户端使用 characterEncoding=utf8 来连接就可以解决问题了。
  2. 如果使用的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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值