通过Java向MySQL插入生僻字
修改MySQL表字段的字符集为utf8mb4
,通过Navicat手动插入是没有问题的。但是Java程序报错
java.sql.SQLException: incorrect string value: '\xF0\xA0\x85\xA4' for column
尝试过将连接字符串指定为jdbc:mysql://localhost:3306/test?useUnicode=true&character_set_server=utf8mb4
也无法解决。
解决
1.更换MySQL驱动为5.1.47
及以上(必须)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
2.JDBC连接字符修改(非必须)
jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&mysqlEncoding=utf8
如果你的数据库字符集是utf8mb4
, 就改为
jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&mysqlEncoding=utf8mb4
3.数据库配置修改(必须)
可以修改 字段、表的字符集为utf8mb4
,两者改一个就行