在MySQL中,表情符号需要4个字节的空间存储,因此如果某个列需要兼容表情存储,需要设置该列的字符集为utf8mb4:
ALTER TABLE `db`.`tablename`
CHANGE COLUMN `content` `content` VARCHAR(45) CHARACTER SET 'utf8mb4' NULL DEFAULT NULL COMMENT '' ;
另外,根据Mysql的文档:
Setting the Character Encoding
The character encoding between client and server is automatically detected upon connection. You specify the encoding on the server using the character_set_server for server versions 4.1.0 and newer, and character_set system variable for server versions older than 4.1.0. The driver automatically uses the encoding specified by the server. For more information, see Server Character Set and Collation.
For example, to use 4-byte UTF-8 character sets with Connector/J, configure the MySQL server with character_set_server=utf8mb4, and leave characterEncoding out of the Connector/J connection string. Connector/J will then autodetect the UTF-8 setting.
To override the automatically detected encoding on the client side, use the characterEncoding property in the URL used to connect to the server.
也就是说,没办法在JDBC客户端直接配置编码方式,因此需要修改mysql服务器的如下属性:
set character_set_server=utf8mb4
要永久生效,在my.ini配置文件中配置:
character_set_server=utf8mb4
同时,JDBC Url的characterEncoding去掉:
datasource.jdbcUrl=jdbc:mysql://127.0.0.1:4360/mydb?useUnicode=true&autoReconnect=true&allowMultiQueries=true
总结一下,为了在Java端支持表情,需要提供4个字节存储的编码方案,具体步骤如下:
1) 设置对应列的编码为utf8mb4
2) 设置服务器编码为utf8mb4
3) JDBC Url中的characterEncoding不配置。
(该属性不支持utf8mb4,配置了非utf8mb4将导致无法写入表情,因此要留空,不配置)
在MySQL中处理表情符号需要设置列的字符集为utf8mb4。根据MySQL文档,服务器端应配置character_set_server=utf8mb4,JDBC连接URL不应包含characterEncoding属性,以自动检测UTF-8设置。为了支持表情,需完成3步:1) 列编码设为utf8mb4;2) 服务器配置utf8mb4;3) JDBC连接URL不配置characterEncoding。
5110

被折叠的 条评论
为什么被折叠?



