大家在使用数据库的时候,总会出现各种各样的编码问题,看了MySQL官方文档后,记录下一些MySQL的编码体系知识,如MySQL有那几层使用编码的地方,MySQL客户端和服务端交互时哪些环节涉及到的编码,和如何指定编码。
基本概念:
mysql> SHOW VARIABLES LIKE 'character%'; +--------------------------+---------------------------------+ | Variable_name | Value | +--------------------------+---------------------------------+ | character_set_client | latin1 | | character_set_connection | latin1 | | character_set_database | latin1 | | character_set_filesystem | binary | | character_set_results | latin1 | | character_set_server | latin1 | | character_set_system | utf8 | | character_sets_dir | D:"mysql-5.0.37"share"charsets" |
mysql的多层字符编码支持
1.server层
作用整个数据库服务器默认编码。
配置点
通过系统变量character_set_server参数指定server层编码
可以在mysqld执行时加入该参数
或者在编辑mysql时候,设置该参数
2.database层
作用数据库级别默认编码。
配置点
通过系统变量character_set_database参数指定database层编码
建表时候指定编码
3.table层
同理,table层的编码设置仅影响当前表的所有未指定编码的列的编码。但这个指定是mysql独有的,而且只能通过sql在建表或修改表时指定, 在标准sql中,没有可指定表编码的sql语法4.column层
作用设置列的编码。
配置点
建表或修改列时设置。这是标准sql语法。
mysql server与client交互时编码如何转换
1.客户端发送语句
character set and collation system variables are involved in handling traffic for the connection between a client and the server. Every client has connection-related character set and collation system variables.The server takes the character_set_client system variable to be the character set in which statements are sent by the client.
在客户端和服务端通讯时,会涉及到另外几个编码设置相关的系统变量的,每个客户端都有属于自己的编码链接相关编码。
服务端使用系统变量character_set_client来处理客户端发来的语句。
2.服务端处理语句
The server uses the character_set_connection and collation_connection system variables. It converts statements sent by the client from character_set_client to character_set_connection (except for string literals that have an introducer such as _latin1 or _utf8)服务端会把客户端发来的语句(以character_set_client 编码)转换为character_set_connection编码。
A character string literal may have an optional character set introducer and COLLATE clause [_charset_name]'string' [COLLATE collation_name]
如:SELECT _latin1'string' COLLATE latin1_danish_ci;
在缺少编码指定是,默认会使用character_set_connection指定的编码。
The character set used for literals that do not have a character set introducer and for number-to-string conversion.
没有前导编码修饰(introducer)的文本和数字到字符的转换会应用character_set_connection编码。
For comparisons of strings with column values, collation_connection does not matter because columns have their own collation, which has a higher collation precedence.
表的列字段与客户端传来的语句进行比较时,会把客户端语句转成列对应编码再进行比较,这是因为列字段拥有更高优先级。
3.服务端返回内容
The character_set_results system variable indicates the character set in which the server returns query results to the client系统变量character_set_results用来把数据以该编码方式返回给客户端。
下面用一张图来大致描述下上面的内容(个人理解所画)