mysql中文乱码问题

1. 查看当前编码

  • 登陆mysql查看
1
show variables like 'character%';

显示如下:

我是图片啦

character_set_database和character_set_server的默认字符集还是latin1

2. 修改字符编码

  • 在[mysqld]字段加入character-set-server=utf8:
1
2
3
4
[mysqld]
port = 3306
socket = /var/lib/mysql/mysql.socket
character-set-server = utf-8
  • 在[client]字段加入default-character-set=utf-8:
1
2
3
4
[client]
port = 3306
socket = /var/lib/mysql/mysql.sock
default-character-set=utf8
  • 在[mysql]字段里加入default-character-set=utf8:
1
2
3
[mysql]
no-auto-rehash
default-character-set=utf8

3. 修改完成后,service mysql restart重启mysql服务就生效

4. 查阅目前的编码

1
SHOW VARIABLES LIKE ‘'character%';

5. 连接层修改编码

若是经过上述设置以后汉子依然乱码则需要在发送查询之前执行

1
set names 'utf8'

他相当于:

1
2
3
SET character_set_client = utf8;
SET character_set_results = utf8;
SET character_set_connection = utf8;

6. 终极解决方案

1
2
3
4
5
6
7
8
[client]
default-character-set=utf8
[mysql]
default-character-set=utf8
[mysqld]
collation-server = utf8_unicode_ci
init-connect=’SET NAMES utf8′
character-set-server = utf8
daodaoliang wechat
点击上面图片后用微信扫描,你就能认识一个有趣的灵魂了呀。
Fork me on GitHub