MySQL编码设置

永久更改:

从my.ini下手

1)修改配置文件
在[client]下添加如下参数,影响系统变量character_set_client和character_set_connection和character_set_results
default-character-set=utf8

在[mysqld]下添加如下参数,影响系统变量character_set_server和character_set_database
default-character-set=utf8

设置完后,启动mysql,我们只需要查看系统变量是否符合我们的要求即可
character_set_client    
character_set_connection
character_set_database  
character_set_results   
character_set_server

如下三个系统变量不需要关心,不会影响乱码
character_set_filesystem    
character_set_system    
character_sets_dir        

 

临时更改:
mysql> SHOW VARIABLES LIKE 'character_set_%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | latin1 |
| character_set_connection | latin1 |
| character_set_database | latin1 |
| character_set_results | latin1 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
7 rows in set (0.00 sec)

 mysql> SHOW VARIABLES LIKE 'collation_%';
+----------------------+-------------------+
| Variable_name | Value |
+----------------------+-------------------+
| collation_connection | latin1_swedish_ci |
| collation_database | latin1_swedish_ci |
| collation_server | latin1_swedish_ci |
+----------------------+-------------------+
3 rows in set (0.00 sec)
默认就是瑞典latin1,一下是换成我们自己的编码,如utf8:
外部访问数据乱码的问题就出在这个connection连接层上,解决方法是在发送查询前执行一下下面这句:

1. SET NAMES 'utf8';

 它相当于下面的三句指令:
 SET character_set_client = utf8;
 SET character_set_results = utf8;
 SET character_set_connection = utf8;

一般只有在访问之前执行这个代码就解决问题了,下面是创建数据库和数据表的,设置为我们自己的编码格式。
2. 创建数据库
 mysql> create database name character set utf8;

3. 创建表
CREATE TABLE `type` (
`id` int(10) unsigned NOT NULL auto_increment,
`flag_deleted` enum('Y','N') character set utf8 NOT NULL default 'N',
`flag_type` int(5) NOT NULL default '0',
`type_name` varchar(50) character set utf8 NOT NULL default '',
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

 4. 修改数据库成utf8的.
mysql> alter database name character set utf8;

5. 修改表默认用utf8.
mysql> alter table type character set utf8;

6. 修改字段用utf8
mysql> alter table type modify type_name varchar(50) CHARACTER SET utf8;
posted @ 2015-02-13 20:56  选择了就坚持  阅读(774)  评论(0编辑  收藏  举报