目前我们在PHP中使用以下命令在应用程序中将字符集设置为UTF-8。
因为这有点开销,所以我们希望将其设置为MySQL中的默认设置。我们可以在/etc/my.cnf或其他位置这样做吗?
SET NAMES 'utf8'
SET CHARACTER SET utf8
我在/etc/my.cnf中寻找了一个默认字符集,但那里没有关于字符集的任何内容。
在这一点上,我做了以下设置MySQL字符集和排序变量为UTF-8:
skip-character-set-client-handshake
character_set_client=utf8
character_set_server=utf8
这是正确的处理方式吗?
这里列出的所有设置都是正确的,但这里是最优和最充分的解决方案:
[mysqld]
init_connect='SET collation_connection = utf8_unicode_ci'
character-set-server = utf8
collation-server = utf8_unicode_ci
[client]
default-character-set = utf8
将这些文件添加到/etc/mysql/my.cnf.
请注意,由于性能问题,我选择utf8_unicode_ci类型的排序。
结果是:
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 | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
mysql> SHOW VARIABLES LIKE 'collation%';
+----------------------+-----------------+
| Variable_name | Value |
+----------------------+-----------------+
| collation_connection | utf8_unicode_ci |
| collation_database | utf8_unicode_ci |
| collation_server | utf8_unicode_ci |
+----------------------+-----------------+
这是当您以非super用户连接时!
例如,SUPER用户和非SUPER用户之间的区别(当然是在utf8_unicode_ci排序的情况下):
SUPER priv用户:
mysql> SHOW VARIABLES LIKE 'collation%';
+----------------------+-----------------+
| Variable_name | Value |
+----------------------+-----------------+
| collation_connection | utf8_general_ci | <---
| collation_database | utf8_unicode_ci |
| collation_server | utf8_unicode_ci |
+----------------------+-----------------+
非super priv用户:
mysql> SHOW VARIABLES LIKE 'collation%';
+----------------------+-----------------+
| Variable_name | Value |
+----------------------+-----------------+
| collation_connection | utf8_unicode_ci |
| collation_database | utf8_unicode_ci |
| collation_server | utf8_unicode_ci |
+----------------------+-----------------+
我写了一篇全面的文章(rus),详细解释了为什么你应该使用一种或另一种选项。所有类型的字符集和排序规则都被考虑:服务器,数据库,连接,表,甚至列。
我希望这篇文章和这篇文章将有助于澄清不清楚的时刻。
更改MySQL字符:
客户端
default-character-set=utf8
mysqld
character_set_server=utf8
我们不应该在mysqld中编写default-character-set=utf8,因为这可能会导致如下错误:
start:任务启动失败
最后:
+--------------------------+----------------------------+
| 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 | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+