首先进入MySQL查看当前默认编码:
mysql> SHOW VARIABLES LIKE 'character%';
+--------------------------+-----------------------------------------------+
| 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 | /rdsdbbin/oscar-5.6.10a.16.21/share/charsets/ |
+--------------------------+-----------------------------------------------+
8 rows in set (0.02 sec)
能够看到大部分都是latin1
,现在想把默认编码改成uft8
可以直接执行set
命令:
SET character_set_client = utf8;
SET character_set_connection = utf8;
SET character_set_database = utf8;
SET character_set_results = utf8;
SET character_set_server = utf8;
然后 mysql> SHOW VARIABLES LIKE 'character%';
可以看到全变为utf8
但是,这只是一种假象。此种方式只在当前状态下有效,当重启数据库服务后失效。
所以想要不出现乱码只有修改MySQL配置文件my.cnf
(windows下my.ini
)。
找到配置文件(Linux下一般是/etc/my.cnf
)
打开文件,标签下没有的要添加,有的就修改:
[client]
default-character-set=utf8
[mysql]
default-character-set=utf8
[mysqld]
default-character-set=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 | /rdsdbbin/oscar-5.6.10a.16.21/share/charsets/ |
+--------------------------+-----------------------------------------------+