小任班长的博客 - characterEncoding
type: channel
link: https://cnxiaocheng.top/tag/characterEncoding/
items: mysql-connector-java指定characterEncoding utf8mb4

mysql-connector-java指定characterEncoding utf8mb4
type: item
date: 2020-06-30T09:00:00+08:00
description: NotesFor 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.官方手册链接：https://dev.mysql.com/doc/connectors/en/connector-j-reference-charsets.html提示mysql-connector-java 版本在8.0.12之前的，包括8.0.12，服务端必须设置character_set_server=utf8mb4;如果不是的话，就算设置了characterEncoding=UTF-8，照样会被设置为MYSQL的 utf8字符集，也就是utf8mb3。对于8.0.13和以后的版本，如果设置了characterEncoding=UTF-8，他会映射到MYSQL的utf8mb4字符集。如果connectionCollation 也和characterEncoding一起设置了，但是不兼容，characterEncoding会被connectionCollation的设置覆盖掉。由于没有Java-Style的utfmb3对应的字符集名称可以用在connection选项charaterEncoding上，唯一的设置utf8mb3的方式就是在连接选项设置utf8mb3 collation（例如utf8_general_ci），这会强制使用utf8mb3字符集，正如上文所述。查看mysql字符集show variables like 'char%'; show variables like 'collation%';