utf8mb4不生效的問題
Mysql數據庫設置的編碼utf8,某個表字段中要插入emoji內容,報 java.sql.SQLException: Incorrect string value: '\xF0\x9F\x98\x88' for column 'message_content' at row 1。在網上搜了一圈,基本上都是先修改數據庫服務器的配置文件,再修改數據庫,再修改表,再修改字段,全都設置爲utf8mb4,這樣把不需要utf8mb4編碼的字段也會都改成utf8mb4,比如下圖這樣。
原本我只想改message_content字段,最終所有varchar字段都變成了utf8mb4。
最要命的還要重啓數據庫,自己測試還好,重啓生產庫就大事件了
其實真正的只要兩步:
1)修改數據庫字段:
ALTER TABLE `oa_t_user_favorite_message` MODIFY COLUMN `message_content` varchar(4000) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '消息內容' ;
2)java中數據庫驅動器設置編碼
我項目基於spring boot,用的是druid數據源,可以參考:https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter
最終我的配置如下
spring:
application:
name: xxx
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
name: test
url: jdbc:mysql://xxx.xxx.xxx:3306/xxx?useUnicode=true&characterEncoding=UTF8&allowMultiQueries=true
username: xxx
password: xxx
driver-class-name: com.mysql.jdbc.Driver
connection-init-sqls: set names utf8mb4 #要設置這個才生效