1. 程式人生 > 實用技巧 >MySql支援emoji表情設定

MySql支援emoji表情設定

使用MySql支援Emoji表情

將欄位設定成utf8mb4

ALTER TABLE `t_order`
MODIFY COLUMN `remark`  varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '訂單備註'

以為這樣就OK了,結果輸入emoji表情,執行insert失敗,失敗資訊為:

2020-12-23 10:35:09 [org.apache.juli.logging.DirectJDKLog:182] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.jdbc.UncategorizedSQLException: 
### Error updating database.  Cause: java.sql.SQLException: Incorrect string value: '\xF0\x9F\x98\x83\xF0\x9F...' for column 'remark' at row 1
### The error may involve com.xima.shop.mapper.OrderMapper.insertUseGeneratedKeys-Inline ### The error occurred while setting parameters ### SQL: INSERT INTO t_order ( state,flag_del,create_user,create_time,update_user,update_time,memo,order_no,order_time,user_id,user_name,user_phone,total_amt,pay_amt,pay_type,pay_no,flag_sms_send,sms_send_count,state_order,cancel_reason,logistics_num,remark ) VALUES ( ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? ) ### Cause: java.sql.SQLException: Incorrect string value: '\xF0\x9F\x98\x83\xF0\x9F...' for column 'remark' at row 1 ; uncategorized SQLException; SQL state [HY000]; error code [1366]; Incorrect string value: '\xF0\x9F\x98\x83\xF0\x9F...' for column 'remark' at row 1; nested exception is java.sql.SQLException: Incorrect string value: '\xF0\x9F\x98\x83\xF0\x9F...' for column 'remark' at row 1] with root cause java.sql.SQLException: Incorrect string value: '\xF0\x9F\x98\x83\xF0\x9F...' for column 'remark' at row 1

  

上網搜尋了一下,還是資料庫伺服器設定的問題,使用命令更新資料庫伺服器的編碼為utf8mb4

set character_set_server=utf8mb4

檢視資料庫編碼show variables like '%char%'

show variables like '%char%'

中間小插曲:

我們的資料庫使用的阿里雲rds,使用root賬號執行set character_set_server=utf8mb4,但是develop賬號仍然看到的是utf8編碼,於是乎,到阿里雲後臺管理介面修改資料庫引數character_set_server =utfmb4

參考以下資料:

https://www.cnblogs.com/java-synchronized/p/7237146.html

https://blog.51cto.com/wangfoye/1913450