Linux下修改MySQL的字符集编码为UTF8

  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_databasecharacter_set_server的默认字符集是latin1

二、最佳修改方法

  修改mysqlmy.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;

  一般经过以上配置,可解决所有的编码问题了,还有问题的可留言。


MySQL 
更新时间:2020-07-27 11:38:12

本文由 新逸Cary 创作,如果您觉得本文不错,请随意赞赏
采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
原文链接:https://blog.xinac.cn/archives/mysql-utf8.html
最后更新:2020-07-27 11:38:12

评论

Your browser is out of date!

Update your browser to view this website correctly. Update my browser now

×