深入淺出MySQL(五) MySQL5.5的中文亂碼坑
阿新 • • 發佈:2019-02-11
這一次的記錄主要是針對mysql5.5版本里面的中文亂碼而言,這裡用到的作業系統是centos7,資料庫是mysql5.5,雲平臺是阿里雲
一、登入MySQL檢視用SHOW VARIABLES LIKE ‘character%’;下字符集,顯示如下:
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
二、修改mysql的my.cnf檔案中的字符集鍵值(注意配置的欄位細節):
1、在[client]欄位里加入default-character-set=utf8,如下:
[client]
port = 3306
socket = /var/lib/mysql/mysql.sock
default-character-set=utf8
2、在[mysqld]欄位里加入character-set-server=utf8,如下:
[mysqld]
port = 3306
socket = /var/lib/mysql/mysql.sock
character-set-server=utf8
3、在[mysql]欄位里加入default-character-set=utf8,如下:
[mysql]
no-auto-rehash
default-character-set=utf8
修改完成後,使用命令:service mysql restart重啟mysql服務就生效。注意:[mysqld]欄位與[mysql]欄位是有區別的。
使用SHOW VARIABLES LIKE ‘character%’;檢視,發現數據庫編碼全已改成utf8。
+--------------------------+----------------------------+
| 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/share/mysql/charsets/ |
+--------------------------+----------------------------+
‘
4、如果上面的都修改了還亂碼,那剩下問題就一定在connection連線層上。解決方法是在傳送查詢前執行一下下面這句(直接寫在SQL檔案的最前面):
SET NAMES ‘utf8’;
它相當於下面的三句指令:
SET character_set_client = utf8;
SET character_set_results = utf8;
SET character_set_connection = utf8;
感興趣的讀者也可以關注小編的個人公眾號,我會定期在上邊分享一些有價值的java知識內容