默认登录mysql之后show variables like ‘%character%’, 出现

 1mysql> show variables like '%character%';
 2+--------------------------+----------------------------+
 3| Variable_name | Value |
 4+--------------------------+----------------------------+
 5| character_set_client | latin1 |
 6| character_set_connection | latin1 |
 7| character_set_database | latin1 |
 8| character_set_filesystem | binary |
 9| character_set_results | latin1 |
10| character_set_server | latin1 |
11| character_set_system | utf8 |
12| character_sets_dir | /usr/share/mysql/charsets/ |
13+--------------------------+----------------------------+
  1. 找到mysql的配置文件,拷贝到etc目录下,第一步很重要

使用find命令查找cnf文件。记得不要去找my.cnf因为它不一定存在,而应该找*.cnf。

 1[root@linuxserver classes] find / -iname *.cnf -print
 2/usr/share/doc/mysql-server-4.1.12/my-medium.cnf
 3/usr/share/doc/mysql-server-4.1.12/my-huge.cnf
 4/usr/share/doc/mysql-server-4.1.12/my-innodb-heavy-4G.cnf
 5/usr/share/doc/mysql-server-4.1.12/my-large.cnf
 6/usr/share/doc/mysql-server-4.1.12/my-small.cnf
 7/usr/share/texmf/web2c/mktex.cnf
 8/usr/share/texmf/web2c/texmf.cnf
 9/usr/share/texmf/web2c/fmtutil.cnf
10/usr/share/texmf/tex/jadetex/jadefmtutil.cnf
11/usr/share/ssl/openssl.cnf
12找到之后,复制一个出来
13cp /usr/share/doc/mysql-server-4.1.12/my-large.cnf /etc/my.cnf
  1. 打开my.cnf修改编码

vi /etc/my.cnf

1[client]下增加default-character-set=utf8
2[mysqld]下增加default-character-set=utf8

同时加上init_connect=‘SET NAMES utf8’ (设定连接mysql数据库时使用utf8编码,以让mysql数据库为utf8运行)。重新启动mysql,执行:sudo /etc/init.d/mysql stop 然后sudo /etc/init.d/mysql start

 1mysql> show variables like %character%;
 2+————————–+—————————-+
 3| Variable_name | Value |
 4+————————–+—————————-+
 5| character_set_client | utf8 |
 6| character_set_connection | utf8 |
 7| character_set_database | utf8 |
 8| character_set_filesystem | binary |
 9| character_set_results | utf8 |
10| character_set_server | utf8 |
11| character_set_system | utf8 |
12| character_sets_dir | /usr/share/mysql/charsets/ |
13+————————–+—————————-+

即使做了以上修改如果直接数据库再创建表,然后存入中文,取出来的会是问号。解决的办法是:
创建数据库的时候指明默认字符集为utf8,如:

1create database test default character set utf8;