最近我在用mybatis插入一條數(shù)據(jù)到mariadb時,報了一個不正確的字符串的錯誤,服務器顯示500錯誤,從控制臺打印相關(guān)的提交數(shù)據(jù)都比較正常估盘,試了英文沒有問題,那么問題就出現(xiàn)在了字符集了骡尽。
錯誤信息主要如下:
### 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默認的字符集是latin1,而服務器字符集為utf-8攀细,當使用中文寫入數(shù)據(jù)庫時箫踩,字符集不正確,便出錯了谭贪。官網(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ù)庫后境钟,確實是這樣。
我們可以使用下面這條SQL語句更改數(shù)據(jù)庫表和數(shù)據(jù)庫的字符集
ALTER TABLE
shopping
.T_PURCHASE_RECORD
MODIFY COLUMNnote
varchar(512) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;
ALTER DATABASE shopping COLLATE = 'utf8_unicode_ci', CHARACTER='utf8';
修改后我們字符集的問題就解決了俭识。不過慨削,雖然我們使用的數(shù)據(jù)庫字符集正確了,如果沒有修改數(shù)據(jù)庫的設置,我們再創(chuàng)建一張表或者數(shù)據(jù)庫缚态,又回遇到這個坑爹的問題磁椒。為了一勞永逸,我們直接修改數(shù)據(jù)庫配置玫芦。
linux下運行vim命令操作my.cnf配置文件
sudo vi /etc/my.cnf
添加一行
[mysqld]
character-set-server = utf8
collation-server = utf8_unicode_ci