MYSQL的字符集支持(Character Set Support)有两个方面:
字符集(Character set)和排序方式(Collation)。
对于字符集的支持细化到四个层次: 服务器(server),数据库(database),数据表(table)和连接(connection)。
查看系统的字符集和排序方式的设定可以通过下面的命令:
mysql>status;
mysql>show variables like ‘character_set_%’;
mysql>show variables like ‘collation’;
查看一个数据表各字段编码用以下命令:
show full columns from table_name;
当我们按照原来的方式存取MySQL数据库时,就算设置了表的默认字符集为utf8并且通过UTF-8编码发送查询,你会发现存入数据库的仍然是乱码。问题就出在这个connection连接层上。解决方法是在发送查询前执行一下下面这句:
1.全局设置
set names ‘utf8’;
它相当于下面的三句指令:
set character_set_client = utf8;
set character_set_results = utf8;
set character_set_connection = utf8;
2.创建数据库
mysql> create database database_name character set utf8;
3.创建表
create table table_name
(
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.修改数据库编码
mysql>alter database database_name character set utf8;
5.修改数据表编码
mysql>alter table table_name character set utf8;
6.修改字段编码
mysql>alter table table_name modify column_name varchar(32) character set utf8;
<<修改数据库编码方法大全>>
修改数据库字符集:
ALTER DATABASE db_name DEFAULT CHARACTER SET character_name [COLLATE …];
把表默认的字符集和所有字符列(CHAR,VARCHAR,TEXT)改为新的字符集:
ALTER TABLE tbl_name CONVERT TO CHARACTER SET character_name [COLLATE …]
如:ALTER TABLE logtest CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
只是修改表的默认字符集:
ALTER TABLE tbl_name DEFAULT CHARACTER SET character_name [COLLATE…];
如:ALTER TABLE logtest DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
修改字段的字符集:
ALTER TABLE tbl_name CHANGE c_name c_name CHARACTER SET character_name [COLLATE …];
如:ALTER TABLE logtest CHANGE title title VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci;
查看数据库编码:
SHOW CREATE DATABASE db_name;
查看表编码:
SHOW CREATE TABLE tbl_name;
查看字段编码:
SHOW FULL COLUMNS FROM tbl_name;