使用JDBC写入Mysql时含emoji内容乱码

JAVA默认是UTF8编码的,按照JDBC文档描述:

To use 3-byte UTF8 with Connector/J set characterEncoding=utf8 and set useUnicode=true in the connection string.

因此连接数据库的字符串描述符应该为:

jdbc:mysql://localhost/DB_NAME?user=USER_NAME&password=PASSWORD&useUnicode=true&characterEncoding=utf8

但含有EMOJI的字符串使用的是UTF8M4编码,即最长为4个字节的变长编码,而不是3个,使用上述描述符插入数据库时会报错:

java.sql.SQLException: Incorrect string value: ‘\xF0\x9F\x92\x94’ for column ‘XXX’ at row 1

根据JDBC文档:

To use 4-byte UTF8 with Connector/J configure the MySQL server with character_set_server=utf8mb4. Connector/J will then use that setting as long as characterEncoding has not been set in the connection string. This is equivalent to autodetection of the character set.

此时应该去掉描述符中的characterEncoding参数,变为:

jdbc:mysql://localhost/DB_NAME?user=USER_NAME&password=PASSWORD&useUnicode=true

同时,Mysql的配置文件my.ini中应该修改character_set_server参数:
my.ini

重启Mysql即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值