1. 程式人生 > 其它 >生僻字"𨭉"引發的mysql資料庫字符集問題(utf8和utfmb4)

生僻字"𨭉"引發的mysql資料庫字符集問題(utf8和utfmb4)

前言:有一個mysql資料庫,由於建庫的時候未使用utf8mb4的字符集,導致插入生僻字亂碼和報錯,經歷了2天的查詢和測試總結了以下經驗供參考。mysql 可以設定資料庫級別,表級別,列級別 字符集編碼;優先順序順序為:資料庫字符集 < 表字符集 < 列字符集;字符集不一致時,以 更小範圍的配置為準。

1、建庫要規範:首先要明白你的用途,生產一定要提前設定標準,如果是中文建議使用utf8mb4,至於utf8和utf8mb4的區別,簡單來說是utf8mb4是4個位元組是utf8的超集,可以相容utf8,可以存特殊字元和表情。

①建立資料庫

CREATE DATABASE testmb4 CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

注意“testmb4”是你設定的庫名

②建立表

CREATE TABLE testtable(id varchar(40) NOT NULL default '',userId varchar(40) NOT NULL default '') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

注意“testtable”是你設定的表名,庫和表的字符集設定好了,基本就不會出問題。

2、如果資料庫、表已經建立可以直接修改資料庫或表的編碼格式,但是生產環境要慎重!!!

①修改資料庫的編碼格式
alter database <資料庫名> character set utf8mb4;

②修改資料表格編碼格式,風險:鎖全表
alter table <表名> character set utf8mb4; 只對表的屬性做變更,不對列上的字符集做轉換
alter table <表名> convert to character set utf8mb4; 對列上的字符集也做轉換

③修改欄位編碼格式
alter table <表名> change <欄位名> <欄位名> <型別> character set utf8mb4;

3、mysql字符集常用命令

①檢視MYSQL資料庫伺服器和資料庫字符集
show variables like '%character%';
show variables like 'collation%';

②檢視MYSQL所支援的字符集
show charset;

③檢視資料表的編碼
show create table <表名>;

④檢視欄位的編碼
show full columns from <表名>;

⑤檢視資料庫編碼:
SHOW CREATE DATABASE db_name;

4、字符集utf8和utf8mb4的報錯現象
①Mysql錯誤1366的解決辦法:Incorrect string value: '\xF0\x9F...' for column 'XXX' at row 1原因是UTF-8編碼有可能是兩個、三個、四個位元組,Emoji表情或者某些特殊字元是4個位元組,而Mysql的utf8編碼最多3個位元組,所以資料插不進去。
解決方案:
第一種就是urlencode後存入資料庫 讀取的時候再urldecode
第二種資料庫欄位改成utf8mb4,注意資料庫的連線方式也要改成utf8mb4

5、資料庫常用命令
①show databases;檢視所有的資料庫,等同於select schema_name from information_schema.schemata\G。\G 替換;,以縱向報表的形式輸出結果,有利於閱讀。

②status 檢視mysql資料庫的執行狀態

③use 命令選擇資料庫 例如 use information_schema,當使用此命令後select schema_name from information_schema.schemata\G,可以為select schema_name from schemata\G

④檢視資料庫中的表
show tables 同樣也可以在information_schema中檢視,show命令是方便使用的簡短模式。
select table_name from tables where table_schema='jblog';

⑤查看錶結構
desc table_name;

⑥查看錶狀態
show table status from db like 條件
可以檢視engine資料庫引擎,version,row、index等資訊

⑦小技巧,當多行命令輸入,發現錯誤後,用\c結束。

⑧查詢資料庫連線
show full processlist;
show status like '%Max_used_connections%';
show status like '%Threads_connected%';#當前連線數
show status like '%table_lock%';#表鎖定
show status like 'innodb_row_lock%';#行鎖定
show status like '%qcache%'; #查詢快取情況
show variables like "%query_cache%";
SHOW STATUS LIKE 'Qcache%';
show variables like "%binlog%";
show status like 'Aborted_clients';#由於客戶沒有正確關閉連線已經死掉,已經放棄的連線數量
show variables like '%max_connections%';//檢視最大連線數量
show variables like '%timeout%';#檢視超時時間
show variables like 'log_%'; #檢視日誌是否啟動