#查看mysql数据库的字符集.
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 | /data/mysql/share/charsets/ |+--------------------------+-----------------------------+8 rows in set (0.01 sec)
#客户端查看时,客户端的字符集.
mysql> set character_set_client=utf8;Query OK, 0 rows affected (0.00 sec)
#客户端查询时,数据库返回给客户使用的字符集.
mysql> set character_set_results=gbk;Query OK, 0 rows affected (0.00 sec)
#数据存储时的连接器,使用gbk和utf都行,存储数据时都会转换为utf8.
set character_set_connection=utf8;
如果客户端插入时和取出时字符集不一样就会乱码?
#设置客户端的字符集为utf8.
mysql> set character_set_client=utf8;Query OK, 0 rows affected (0.00 sec)
#创建数据库t5.
mysql> create table t5 ( name char(20) );Query OK, 0 rows affected (0.02 sec)
#插入使用的字符集utf8;
mysql> insert into t5 values ("中国");Query OK, 1 row affected (0.00 sec)
#查看时没问题.
mysql> select * from t5;+--------+| name |+--------+| 中国 |+--------+1 row in set (0.00 sec)
#取出时让服务端返回给gbk的字符集.
mysql> set character_set_results=gbk;Query OK, 0 rows affected (0.00 sec)
#设置服务端返回时gbk就乱码了.
mysql> select * from t5;+------+| name |+------+| א¹|+------+1 row in set (0.02 sec)
注意:我使用的客户端xshell链接,字符集为utf8字符集.
#如果把客户端/连接器/服务端都设置为utf8肯定不会乱码.
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_results=utf8;Query OK, 0 rows affected (0.00 sec)mysql> select * from t5;+--------+| name |+--------+| 中国 |+--------+1 row in set (0.00 sec)
#使用names可以直接将这三条都设置为同一个字符集.
mysql> set names gbk;Query OK, 0 rows affected (0.00 sec)
#查看字符集发现clien/connection/results都变为gbk.
mysql> show variables like "%character%";+--------------------------+-----------------------------+| Variable_name | Value |+--------------------------+-----------------------------+| character_set_client | gbk || character_set_connection | gbk || character_set_database | utf8 || character_set_filesystem | binary || character_set_results | gbk || character_set_server | utf8 || character_set_system | utf8 || character_sets_dir | /data/mysql/share/charsets/ |+--------------------------+-----------------------------+8 rows in set (0.00 sec)