中文無法插入mariadb數(shù)據(jù)庫解決辦法

最近我在用mybatis插入一條數(shù)據(jù)到mariadb時(shí),報(bào)了一個(gè)不正確的字符串的錯(cuò)誤,服務(wù)器顯示500錯(cuò)誤,從控制臺(tái)打印相關(guān)的提交數(shù)據(jù)都比較正常,試了英文沒有問題,那么問題就出現(xiàn)在了字符集了。


錯(cuò)誤截圖

錯(cuò)誤信息主要如下:

### Error updating database. Cause: java.sql.SQLDataException: (conn=329) Incorrect string value: '\xE4\xB9\xB0:15...' for column 'note' at row 1
### The error may exist in com/xiao/shopping/demo/dao/PurchaseRecordDao.java (best guess)
### The error may involve com.xiao.shopping.demo.dao.PurchaseRecordDao.insertPurchaseRecord-Inline
### The error occurred while setting parameters
### SQL: insert into T_PURCHASE_RECORD( id,user_id,product_id,price,quantity,sum,purchase_date ,note ) values ( ?,?,?,?,?,?,now(),? )
### Cause: java.sql.SQLDataException: (conn=329) Incorrect string value: '\xE4\xB9\xB0:15...' for column 'note' at row 1
; (conn=329) Incorrect string value: '\xE4\xB9\xB0:15...' for column 'note' at row 1; nested exception is java.sql.SQLDataException: (conn=329) Incorrect string value: '\xE4\xB9\xB0:15...' for column 'note' at row 1] with root cause

后面上了mariaDB官網(wǎng)看,原來mariadb默認(rèn)的字符集是latin1,而服務(wù)器字符集為utf-8,當(dāng)使用中文寫入數(shù)據(jù)庫時(shí),字符集不正確,便出錯(cuò)了。官網(wǎng)原話如下:

In MariaDB, the default character set is latin1, and the default collation is latin1_swedish_ci
When changing a character set and not specifying a collation, the default collation for the new character set is always used.

我們使用一條命令查看表的字符集

show create table [表格名稱]
show create database [數(shù)據(jù)庫名稱]

查看數(shù)據(jù)庫后,確實(shí)是這樣。

數(shù)據(jù)庫表字符集打印結(jié)果

數(shù)據(jù)庫字符集

我們可以使用下面這條SQL語句更改數(shù)據(jù)庫表和數(shù)據(jù)庫的字符集

ALTER TABLE shopping.T_PURCHASE_RECORD
MODIFY COLUMN note varchar(512) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;
ALTER DATABASE shopping COLLATE = 'utf8_unicode_ci', CHARACTER='utf8';

修改字符集后重新post數(shù)據(jù)

修改后我們字符集的問題就解決了。不過,雖然我們使用的數(shù)據(jù)庫字符集正確了,如果沒有修改數(shù)據(jù)庫的設(shè)置,我們再創(chuàng)建一張表或者數(shù)據(jù)庫,又回遇到這個(gè)坑爹的問題。為了一勞永逸,我們直接修改數(shù)據(jù)庫配置。

linux下運(yùn)行vim命令操作my.cnf配置文件
sudo vi /etc/my.cnf
添加一行
[mysqld]
character-set-server = utf8
collation-server = utf8_unicode_ci

my.cnf配置文件
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容