相信技术的力量

设置Mysql字符集编码为UTF-8,解决中文乱码

微信公众号开发,获取到的用户昵称为乱码,排查结果为Mysql数据库的默认字符集编码问题,要解决中文乱码,必须设置默认字符集为UTF-8

登录mysql,通过命令查看字符集编码:

mysql> show variables like "char%";

结果如下:

+--------------------------+----------------------------+
| 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_databasecharacter_set_server的编码默认为latin1,因此需要修改为UTF-8

修改Mysql配置文件

vim /etc/my.cnf

在【mysqld】下方添加character_set_server=utf8,位置如下:

[mysqld]
...
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

character_set_server=utf8

设置完成后,:wq保存,并重启mysql服务

sudo systemctl restart mysqld

再次查看数据库字符集编码,发现已经全部改成UTF-8了:

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.01 sec)

(完)

参考链接:

http://www.2cto.com/database/201311/255324.html

⬆️

Mysql工作日志 2017-12-14