今天review同事的代码,发现从数据库查找包含中文的记录一概查不出来,将中文插入到数据表后又是“??”这类的乱码,这应该是字符集的问题了。

1、先看看目前的字符集是什么?

客户端可运行:

SHOW VARIABLES

我的服务端是安装在linux下的,首先进入linux:

1)输入mysql -u root

2)输入show variables like 'character%'

显示结果:

mysql> show variables like 'character%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | latin1                       |
| character_set_database   | utf8                       |
| 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)

3)找到my.cnf文件

退出mysql,进入路径 /etc/mysql/my.cnf文件

输入vi my.cnf

输入i,进入编辑模式

添加或替换一下内容:

[client]

default-character-set=utf8

[mysqld]

default-character-set=utf8

init_connect='SET NAMES utf8'  (设定连接mysql数据库时使用utf8编码,以让mysql数据库为utf8运行)

编辑完后,如果想保存退出,则先按 ESC 键,然后输入 :wq ,不想保存的话,则输入 :q!  搞定

4) 重新启动mysql服务

输入service mysqld restart

更多重新启动mysql服务的内容请参见

http://hi.baidu.com/breezelark/blog/item/d9124622fc7698efd7cae2b2.html

5)重新查看字符集

 

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)


再次查询和插入,则没有中文乱码的问题了。