关于mysql在linux下乱码问题的解决
mysql的乱码问题一直比较头痛,由于它默认的字符集是latin,在数据库中执行mysql>SHOW VARIABLES LIKE 'character_set_%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | latin |
| character_set_connection | latin |
| character_set_database | latin |
| character_set_filesystem | binary |
| character_set_results | latin |
| character_set_server | latin |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
一般我们开发的系统都会用到需要显示中文的情况,网页一般就会设置成GBK,比如页面开头都会写上(以jsp为例子):
要保证不乱码,要确保从数据库到页面显示采用统一的字符集,网上很多都建议采用统一的UTF-8来处理,根据我的实践发现,这样做的唯一缺点,就是很多mysql的前台工具好象对UTF-8支持的有问题,比如我用的EMS SQL Manager 2005 for MySql,我将所有的都设置成UTF-8后,它对于中文就是显示?????,虽然在程序中运行无误.
下面我就先说说我是怎么做的,将mysql设置成GBK的字符集,保证中文无乱码:
(1)从/usr/share/mysql目录下copy 文件my-medium.cnf 到/etc下,并将改文件改名为my.cnf.
(2)在my.cnf(window下是my.ini文件)文件中找到 [mysqld] 在这里添加:default-character-set = GBK ,然后找到[mysql] 在这里也添加上default-character-set = GBK,保存后退出.(当然若要设置成UTF-8也一样,改成default-character-set = UTF-8即可).
然后重起mysql server,(去/etc/init.d/执行./mysql stop & ./mysql start),再次去数据库执行mysql>SHOW VARIABLES LIKE 'character_set_%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | gbk |
| character_set_connection | gbk |
| character_set_database | gbk |
| character_set_filesystem | binary |
| character_set_results | gbk |
| character_set_server | gbk |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
会发现字符集都变成GBK了.
(3)建立GBK编码的数据库,mysql>CREATE DATABASE d4 DEFAULT CHARACTER SET gbk COLLATE gbk_chinese_ci;(修改存在的数据库的字符集 mysql>alter database testdb character set GBK;)