Caused by: java.sql.SQLException: Incorrect string value: '\xF0\x9F\x98\x84' for column 'NickName' at row 1 at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2734) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
UTF-8編碼有可能是兩個、三個、四個字節。Emoji表情是4個字節,而Mysql的utf8編碼最多3個字節,所以數據插不進去。
解決方法:
1、修改mysql配置文件my.ini
找到配置文件是關鍵,可在window服務找到mysql的服務,右鍵屬性查看,如圖:
打開配置文件,在響應的節點追加以下內容:
[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'
2、修改數據庫及表結構,命令行如下:
ALTER DATABASE ‘database’ CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
ALTER TABLE 'tablename' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE 'tablename' modify 'columnName' text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
3、修改java程序中的數據庫連接字符串,不要設置 characterEncoding,設置autoReconnect=true,連接串如下:
jdbc:mysql://127.0.0.1:3306/dbname?useUnicode=true&autoReconnect=true&allowMultiQueries=true
4、最后一步,重啟mysql數據庫,重啟web服務器。
ok,搞定!