21

I'm seeing

OperationalError (1267, "Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='")

It looks like some of my variables are UTF8 strings

'name': 'p\xc7\x9d\xca\x87\xc9\x9f\xc4\xb1\xc9\xa5s Badge'

Is this a configuration issue? If so, how can i solve it? I'd like to handle everything in Unicode (I think).

4

3 回答 3

45

您可以通过 shell 更改表编码:

$ manage.py shell
>>> from django.db import connection
>>> cursor = connection.cursor()
>>> cursor.execute('SHOW TABLES')
>>> results=[]
>>> for row in cursor.fetchall(): results.append(row)
>>> for row in results: cursor.execute('ALTER TABLE %s CONVERT TO CHARACTER SET utf8 COLLATE     utf8_general_ci;' % (row[0]))

https://mayan.readthedocs.org/en/v0.13/faq/index.html

于 2012-03-12T14:26:18.423 回答
12

看来您的数据库默认为 latin1_swedish_ci,因此不能接受所有 utf8 字符。您需要更改 MySQL 数据库表的配置以使用 utf8_general_ci。可以在MySQL 性能博客上找到一篇关于此的好博文(带有工具链接)

于 2009-07-02T14:17:40.420 回答
1

您将在 django 设置文件中添加选项,如下所示:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {'charset': 'utf8mb4'},
        'NAME': 'sarpanchDb',
        'USER': 'root',
        'PASSWORD': 'tiger',
        'HOST': 'localhost',
        'PORT': '',
    },
}

您还需要在 /etc/mysql/my.cnf 文件中进行更改

[mysql]
default-character-set=utf8mb4

[mysqld]
character-set-server=utf8mb4
collation-server=utf8mb4_unicode_ci

然后重启mysql服务

sudo service mysql restart

使用以下查询交叉检查它是否有效

SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR 
Variable_name LIKE 'collation%';

你应该得到以下输出

+--------------------------+--------------------+
| Variable_name            | Value              |
+--------------------------+--------------------+
| character_set_client     | utf8mb4            |
| character_set_connection | utf8mb4            |
| character_set_database   | utf8mb4            |
| character_set_filesystem | binary             |
| character_set_results    | utf8mb4            |
| character_set_server     | utf8mb4            |
| character_set_system     | utf8               |
| collation_connection     | utf8mb4_unicode_ci |
| collation_database       | utf8mb4_unicode_ci |
| collation_server         | utf8mb4_unicode_ci |
+--------------------------+--------------------+
10 rows in set (0.00 sec)
于 2019-05-02T17:23:18.227 回答