注意 安装mysql时最好设置成utf8格式字符编码,安装过程中有一个界面是设置字符的,选择第三个,并从右边下拉框中选择utf8即可,这样mysql的字符集变成utf8了。
一、通过MySQL命令行查看、修改:
1. 查看字符编码:
mysql> show variables like 'character_set_%'; 或 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.03 sec)
mysql> show variables like 'collation_%';
+----------------------+-----------------+
| Variable_name | Value |
+----------------------+-----------------+
| collation_connection | utf8_general_ci |
| collation_database | utf8_general_ci |
| collation_server | utf8_general_ci |
+----------------------+-----------------+
3 rows in set (0.04 sec)
-------------------------------------------------------------------------
2.修改默认字符集
使用mysql的命令修改:(set 大小写不影响)
mysql> SET character_set_client = utf8 ;
mysql> SET character_set_connection = utf8 ;
mysql> SET character_set_database = utf8 ;
mysql> SET character_set_results = utf8 ;
mysql> SET character_set_server = utf8 ;
mysql> SET collation_connection = utf8 ;
mysql> SET collation_database = utf8 ;
mysql> SET collation_server = utf8 ;
mysql>exit;
二、还有一种方法就是直接修改mysql的配置文件my.ini中的default-character-set=latin1和character-set-server=latin1
修改default-character-set=utf8 它相当于下面的三句指令:
set character_set_client =utf8;
set character_set_connection =utf8;
set character_set_results =utf8;
修改character-set-server=utf8 它相当于下面的三句指令:
set character_set_database=utf8;
set character_set_server =utf8;
最后在服务中重启mysql.才能生效。(php集成环境中可以通过控制界面直接启动mysql)
注意:
SET NAMES 'utf8'; //该句话一定要放在数据库服务器连接语句【$connection=mysql_connect($db_host,$db_user,$db_psw)or die("连接服务器失败");】之后
即可显示正常(只要数据库里信息的字符正常)。
它相当于下面的三句指令:
SET character_set_client = utf8;SET character_set_results = utf8;
SET character_set_connection = utf8;
看看这3个变量的作用:
信息输入路径:client→connection→server;
信息输出路径:server→connection→results。
换句话说,每个路径要经过3次改变字符集编码。以出现乱码的输出为例,server里utf8的数据,传入connection转为latin1,传入results转为latin1,utf-8页面又把results转过来。如果两种字符集不兼容,比如latin1和utf8,转化过程就为不可逆的,破坏性的。
但这里要声明一点,“SET NAMES UTF8”作用只是临时的,MySQL重启后就恢复默认了。
总结:为了让你的网页能在更多的服务器上正常地显示,还是加上“SET NAMES UTF8”吧,即使你现在没有加上这句也能正常访问。