在 django live 应用程序中将 mysql 数据库从“utf8”更改为“utf8mb4”对数据的影响

Sak*_*ham 0 python mysql database django encoding

我正在使用 Apache 2 通过 MySQL 后端为 Django 应用程序提供服务。我已将数据库的字符集配置为“utf8”,我也想存储表情符号,所以我需要将编码更改为“utf8mb4”,我只是想知道如果我更改配置会影响我的数据吗?这是我的 mysql.cnf 文件

[client]
database = 'databasename'
user = 'username'
password = 'password'
default-character-set = utf8
Run Code Online (Sandbox Code Playgroud)

这是我的 mysql 数据库的 django 设置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/mysql.cnf'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它会对我之前保存的数据产生什么影响?另外,我应该如何做,我应该直接将其添加default-character-set = utf8mb4到我的默认配置文件中吗?

Ric*_*mes 5

姜戈:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        ...
        'OPTIONS': {
                    'charset': 'utf8mb4',
                    'use_unicode': True, },
    },
}
Run Code Online (Sandbox Code Playgroud)

我的.cnf:

[mysqld]
character-set-server=utf8mb4
default-collation=utf8mb4_unicode_520_ci

[client]
default-character-set=utf8mb4
Run Code Online (Sandbox Code Playgroud)

但是,您还需要更改表定义

假设该表已CHARACTER SET utf8正确编码为 utf8;想要 utf8mb4:

ALTER TABLE tbl CONVERT TO CHARACTER SET utf8mb4;
Run Code Online (Sandbox Code Playgroud)

更改一列是CHARACTER SET utf8用 utf8 正确编码的;并且您想要 utf8mb4 而不触及其他列:

ALTER TABLE tbl MODIFY COLUMN col ... CHARACTER SET utf8mb4;
Run Code Online (Sandbox Code Playgroud)

(请务必保持其他规范相同 - VARCHAR、NOT NULL 等)

更多的

表中任何正确编码的数据都将转换为 utf8mb4(实际上是无操作)。

去体验:

CREATE TABLE test LIKE existing_table;
SHOW CREATE TABLE;  -- to see the old schema
INSERT INTO test SELECT * FROM existing_table;
ALTER TABLE test CONVERT TO CHARACTER SET utf8mb4;
SHOW CREATE TABLE;  -- to see the new schema
SELECT * FROM test;  -- to see the data
SELECT col, HEX(col) FROM test WHERE ...;  -- to check encoding
Run Code Online (Sandbox Code Playgroud)

在哪里

`existing_table` is some table with utf8 characters in it.
`col` and `...` limit the SELECT to one row with accented letters.
Run Code Online (Sandbox Code Playgroud)