最近在centos6.5下部署web项目时网页出现中文乱码的问题,在排除掉php之后,把问题锁定在mysql的编码方式上。
解决方法如下:
首先进入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/ |
+--------------------------+----------------------------+
mysql的默认编码方式是latin1而不是utf8
一般来说,有三种处理方法:
1.在创建数据库的时候默设置编码格式为utf8,这种方法我之前用过,但没有解决问题
2.在mysql命令行中通过命令设置编码格式,比如:
set character_set_client = utf8;
....
这种方法在重启mysql之后设置会失效
3.最根本的解决方法是直接修改mysql的配置文件,文件路径是/etc/my.cnf,进入vim编辑界面,进行如下修改:
--在[mysqld]下添加:
default-character-set=utf8
character_set_server=utf8
--在[mysql]下添加:
default-character-set=utf8
--在[mysql.server]下添加:
default-character-set=utf8
--在[mysqld_safe]下添加:
default-character-set=utf8
--在[client]下添加:
default-character-set=utf8
重启mysqld服务,再进入mysql命令行输入SHOW VARIABLES LIKE ‘character_set_%’,这时配置已经生效
+--------------------------+----------------------------+
| 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/ |
+--------------------------+----------------------------+
另外,原数据库需要删除再重新导入数据库文件,打开浏览器测试,乱码问题解决