默认情况下MySQL数据库使用的是拉丁(lantin1)字符进行编码;
如输入命令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     | latin1                      |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+

可以看到字符编码都是latin1,拉丁字符是无法支持中文的,所以我们插入中文时,肯定会造成一堆乱码

解决乱码

修改my.cnf 配置文件:在配置文件中加入编码设置,默认情况(Linux环境下装MySQL时)是没有字符设置的,默认为Latin1;
修改内容如下:

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

symbolic-links=0

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
character-set-server=utf8


[mysql]
default-character-set=utf8

[client]
default-character-set=utf8

在修改my.cnf,并systemctl restart mysqld;重启服务后,编码即可生效

+--------------------------+----------------------------+
| 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/ |
+--------------------------+----------------------------+

Q.E.D.


寻门而入,破门而出