在使用Mac電腦進(jìn)行MySQL數(shù)據(jù)庫開發(fā)時,可能會遇到中文亂碼的問題。這是由于MySQL默認(rèn)的字符集為Latin1,不支持中文字符集。
mysql>show variables like '%char%'; +--------------------------+--------------------+ | Variable_name | Value | +--------------------------+--------------------+ | character_set_client | latin1 | | character_set_connection | latin1 | | character_set_database | latin1 | | character_set_filesystem | binary | | character_set_results | latin1 | | character_set_server | latin1 | | character_set_system | utf8 | | character_sets_dir | /usr/local/mysql-5.7.29-macos10.15-x86_64/share/mysql/charsets/ | +--------------------------+--------------------+
解決方法是將MySQL數(shù)據(jù)庫的字符集改為utf8。
mysql>set character_set_client = utf8; mysql>set character_set_connection = utf8; mysql>set character_set_database = utf8; mysql>set character_set_results = utf8; mysql>set character_set_server = utf8;
修改后再查看字符集,應(yīng)該已經(jīng)變成了utf8。
mysql>show variables like '%char%'; +--------------------------+--------------------+ | Variable_name | Value | +--------------------------+--------------------+ | character_set_client | utf8 | | character_set_connection | utf8 | | character_set_database | utf8 | | character_set_filesystem | binary | | character_set_results | utf8 | | character_set_server | utf8 | | character_set_system | utf8 | | character_sets_dir | /usr/local/mysql-5.7.29-macos10.15-x86_64/share/mysql/charsets/ | +--------------------------+--------------------+
在創(chuàng)建表時,也需要將表的字符集設(shè)置為utf8。
create table test ( id int primary key auto_increment, name varchar(20) not null, content text not null ) engine=InnoDB default charset=utf8;
這樣,在插入、更新、查詢時,中文字符就不會出現(xiàn)亂碼問題了。