我們經常會碰到mysql數據庫保存中文亂碼這個問題,今天我又碰到了,我的原因是以前使用的是latin1的默認編碼, 以前的程序插入中文亂碼 ,以前的寫法:在source中加入charset=gb2312,然後在插入前執行set names gb2312即可
latin1即是iso8859-1, 所以在插入之前需要將內容轉換為iso8859-1, 如下:
代碼如下
復制代碼
Encoding iso88591 = Encoding.GetEncoding("iso8859-1");
Encoding df = Encoding.Default;
byte[] gb2312bytes = df.GetBytes(content);
//byte[] asciiBytes = Encoding.Convert(df, iso88591, gb2312bytes);
tring str = iso88591.GetString(gb2312bytes);
這樣轉換之後 ,source中不用加入charset參數 ,程序中也不需要先執行set names **, 即可正常插入
如果是mysql服務器我們不知道編碼可參考下面方法解決
mysql的字符集是utf8的,光看這點害人不淺。登錄linux,mysql -uroot -p,進入mysql。
命令:SHOW VARIABLES LIKE 'character_set_%';
代碼如下
復制代碼
+--------------------------+----------------------------+
| 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/share/mysql/charsets/ |
+--------------------------+----------------------------+
只有character_set_system是utf8。
vi /etc/my.cnf
mysql的默認配置文件以及目錄
編輯如下:
[mysqld]
代碼如下
復制代碼
default-character-set=utf8
之後:service mysql stop
service mysql start
重啟後,再次查看SHOW VARIABLES LIKE 'character_set_%';
代碼如下
復制代碼
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | latin1 |
| character_set_connection | latin1 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | latin1 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
此時,character_set_database已經是utf8,工程已經不再亂碼。
可以再添加如下一句:
代碼如下
復制代碼
[client]
default-character-set=utf8
也可登錄的時候, 要用以下命令:mysql --default-character-set=utf8 -u root -p
則:
代碼如下
復制代碼
+--------------------------+----------------------------+
| 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/ |
最後如果你是php連接mysql中文亂碼可參考下辦法解決
就是在mysql_connect後面加一句SET NAMES UTF8,即可使得UTF8的數據庫消除亂碼,對於GBK的數據庫則使用SET NAMES GBK,代碼如下:
代碼如下
復制代碼
$mysql_mylink = mysql_connect($mysql_host, $mysql_user, $mysql_pass);
mysql_query("SET NAMES 'GBK'");