最近项目中使用Mysql5.5.3+时(使用的是utf8字符集),在插入HTML文本(insert into...)至数据时时报如下错误:
java.sql.SQLException: Incorrect string value: '\xF0\x9F\x92\x94' for column 'name' at row 1
以上错误是因为HTML文本中包含了MySql字符集不支持的字符,例如:Emoji表情
查询版本语句:
select version();
打开mysql配置文件mysql/my.cnf或mysql/my.ini, 并且添加如下内容:
[client]
default-character-set=utf8mb4
[mysql]
default-character-set=utf8mb4
[mysqld]
character-set-client-handshake=FALSE
character-set-server=utf8mb4
collation-server=utf8mb4_unicode_ci
init_connect='SET NAMES utf8mb4'
1、Windows请到服务管理界面重新启动MySql服务:services.msc
2、Linux请执行命令:/etc/init.d/mysql restart
执行查看数据库字符集命令:
SHOW VARIABLES WHERE Variable_name LIKE 'character_set_%' OR Variable_name LIKE 'collation%';
+--------------------------+--------------------+
| Variable_name | Value |
+--------------------------+--------------------+
|| character_set_client | utf8mb4
|| character_set_connection | utf8mb4
|| character_set_database | utf8mb4
|| character_set_filesystem | binary
|| character_set_results | utf8mb4
|| character_set_server | utf8mb4
|| character_set_system | utf8
|| collation_connection | utf8mb4_unicode_ci
|| collation_database | utf8mb4_unicode_ci
|| collation_server | utf8mb4_unicode_ci
+--------------------------+--------------------+
必须保证:
character_set_client/character_se_connection/character_set_database/character_set_results/character_set_server为utf8mb4。
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=true
jdbc.username=username
jdbc.password=password
注意:jdbc.url的内容,characterEncoding=utf8可以配自动识别为utf8bm4
ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE table_name table_name CHANGE column_name VARCHAR(1024) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
注意:mysql-connector-java驱动在5.1.13之前是不支持utf8mb4,请使用5.1.13以后的版本。