在MySQL中,表情符号需要4个字节的空间存储,因此如果某个列需要兼容表情存储,需要设置该列的字符集为utf8mb4:
1 ALTER TABLE `db`.`tablename`
2 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服务器的如下属性:
1 set character_set_server=utf8mb4
要永久生效,在my.ini配置文件中配置:
1 character_set_server=utf8mb4
同时,JDBC Url的characterEncoding去掉:
1 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将导致无法写入表情,因此要留空,不配置)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。