mysql字符设置

时间:2022-04-29 17:23:51

MySQL字符集设置

mysql>CREATE DATABASE IF NOT EXISTS mydb default charset utf8 COLLATE utf8_general_ci;//数据库mysql>create table mytable (name varchar(20) not null default '')type=myisam default charset utf8;//数据表

系统变量:

– character_set_server:默认的内部操作字符集

– character_set_client:客户端来源数据使用的字符集

– character_set_connection:连接层字符集

– character_set_results:查询结果字符集

– character_set_database:当前选中数据库的默认字符集

– character_set_system:系统元数据(字段名等)字符集

– 还有以collation_开头的同上面对应的变量,用来描述字符序。

• 用introducer指定文本字符串的字符集:

mysql> show variables like 'character_set_%';

mysql> set character_set_client=utf8;

Query OK, 0 rows affected (0.00 sec)

mysql> set character_set_connection=utf8;

Query OK, 0 rows affected (0.00 sec)

mysql> set character_set_database=utf8;

Query OK, 0 rows affected (0.00 sec)

mysql> set character_set_results=utf8;

Query OK, 0 rows affected (0.00 sec)

mysql> set character_set_server=utf8;

Query OK, 0 rows affected (0.02 sec)

mysql> set character_set_system=utf8;

ERROR 1238 (HY000): Variable 'character_set_system' is a read only variable

mysql> set collation_connection=utf8;

ERROR 1273 (HY000): Unknown collation: 'utf8'

mysql> show variables like 'character_set_%';

mysql> set collation_database=utf8;

ERROR 1273 (HY000): Unknown collation: 'utf8'

mysql> set collation_database=utf8_general_ci;

Query OK, 0 rows affected (0.00 sec)

mysql> set collation_database=utf8_general_ci;

Query OK, 0 rows affected (0.00 sec)

mysql> set collation_server=utf8_general_ci;

Query OK, 0 rows affected (0.00 sec)

mysql> show variables like 'collation_%';

建表后如果后续需要修改表的默认字符集,可以通过ALTER TABLE来修改表的默认编码

mysql>alter database maildb default character set utf8;//修改数据库的字符集

mysql>alter table mailtable default character set utf8;//修改表的字符集

但可能只改了表定义的默认编码,对于每个列的已有字段的内容还是使用以前的编码,已有表数据不会做编码转换。

mysql>ALTER TABLE tablename CONVERT TO CHARACTER SET utf8;来修改列的编码

但这里要注意已有内容编码转换要注意编码可转换,不会成为乱码

永久修改mysql字符集设置(默认为latin1)

ls -l | grep my.cnf (在/etc下查找是否有my.cnf文件存在)

#vim
 /etc/my.cnf

[client]
port =3306
socket = /var/lib/mysql/mysql.sock
default-character-set=utf8 [mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
set-variable=key_buffer=256M
set-variable=table_cache=256
set-variable=sort_buffer=1M
set-variable=myisam_sort_buffer_size=64M
set-variable=net_buffer_length=8K
set-variable=record_buffer=1M
set-variable=thread_cache=8
set-variable=thread_concurrency=8
default-character-set=utf8
character-set-server = utf8
collation-server = utf8_general_ci
init_connect = 'SET collation_connection = utf8_general_ci'
init_connect='SET NAMES utf8'

然后再重启mysql

service mysqld stop

service mysqld start