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

錯(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í)是這樣。


我們可以使用下面這條SQL語句更改數(shù)據(jù)庫表和數(shù)據(jù)庫的字符集
ALTER TABLE
shopping.T_PURCHASE_RECORD
MODIFY COLUMNnotevarchar(512) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;
ALTER DATABASE shopping COLLATE = 'utf8_unicode_ci', CHARACTER='utf8';

修改后我們字符集的問題就解決了。不過,雖然我們使用的數(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
