MySQL安装后的默认字符集如果不是UTF8,可能会有中文乱码等情况发生,只需修改字符集编码为UTF8即可解决。
一、查看默认编码
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/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)
可以看到,character_set_database
和character_set_server
的默认字符集是latin1
二、最佳修改方法
修改mysql
的my.cnf
配置文件
(1)[client]节点
[client]
...
default-character-set=utf8
(2)[mysqld]节点
[mysqld]
...
character-set-server=utf8
(3)[mysql]节点
[mysql]
...
default-character-set=utf8
(4)注意mysqld
节点和另外两个节点的属性名称不同,注意区分!
三、测试效果
配置文件修改后重启mysql
服务生效。
重启服务后查看效果:
mysql> SHOW VARIABLES LIKE 'character%';
+--------------------------+----------------------------+
| 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/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)
四、补充说明
如果还有乱码,可以试试以下方法。
[mysqld]
...
character-set-server = utf8
init-connect = 'SET NAMES utf8'
效果相当于:
SET character_set_client = utf8;
SET character_set_results = utf8;
SET character_set_connection = utf8;
一般经过以上配置,可解决所有的编码问题了,还有问题的可留言。
本文作者为新逸网络,转载请注明。