但发现了一个问题,iPhone上有Emoji表情,插入Mysql时失败了,报如下异常:
- java.sql.SQLException: Incorrect string value: '\xF0\x9F\x92\x94' for column 'name' at row 1
- at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
- at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3593)
- at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3525)
- at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1986)
- at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2140)
- at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2620)
- at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1662)
- at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1581)
上百度Google一下,终于找到了答案。UTF-8编码有可能是两个、三个、四个字节。Emoji表情是4个字节,而Mysql的utf8编码最多3个字节,所以数据插不进去。解决方案就是:将Mysql的编码从utf8转换成utf8mb4。网上应该能搜到一大堆修改Mysql编码的方法。
我是这么做的,可能有些修改没有必要,但最终我还是解决了问题:
1. 修改my.cnf (window下是my.ini; Linux下是my.cnf)
[mysqld]
character-set-server=utf8mb4
[mysql]
default-character-set=utf8mb4
修改后重启Mysql
2. 以root身份登录Mysql,修改环境变量,将character_set_client,character_set_connection,character_set_database,character_set_results,character_set_server 都修改成utf8mb4
mysql>
SET character_set_client = utf8mb4;
SET character_set_connection = utf8mb4;
SET character_set_database = utf8mb4;
SET character_set_results = utf8mb4;
SET character_set_server = utf8mb4;
3. 将已经建好的表也转换成utf8mb4
命令:alter table TABLE_NAME convert to character set utf8mb4 collate utf8mb4_bin; (将TABLE_NAME替换成你的表名)
至此,OK了!
https://www.cnblogs.com/zy-jiayou/
本博客文章均为作者原创,转载请注明作者和原文链接。