SQLAlchemy对于MySQL的默认字符集是什么?

huangapple go评论73阅读模式
英文:

What is the default character set in SQLAlchemy for MySQL?

问题

我想将数据库从utf8mb3迁移到utf8mb4。在我的代码中,我创建了一个引擎:

url = make_url(database_url)
if 'charset' not in url.query:
    url = url.update_query_pairs([('charset', 'utf8')])
create_engine(str(url))

我的数据库使用字符集utf8mb4,在my.cnf中有以下配置:

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

[client]
default-character-set = utf8mb4

[mysql]
default-character-set = utf8mb4

所以问题是:当我创建我的SQLAlchemy引擎时,字符集将是什么?它将是utf8mb4吗?

英文:

I want to move a database from utf8mb3 to utf8mb4. In my code I create an engine:

url = make_url(database_url)
if 'charset' not in url.query:
	url = url.update_query_pairs([("charset", "utf8")])
create_engine(str(url))

I have database with character set utf8mb4 and I have these entries in my.cnf:

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

[client]
default-character-set = utf8mb4

[mysql]
default-character-set = utf8mb4

So the question is: When I create my SQLAlchemy engine, what will the character set be? Will it be utf8mb4?

答案1

得分: 1

将字符集设置为utf8mb4,而不是utf8mb3,通过以下方式:

url = base_url.update_query_pairs([("charset", "utf8mb4")])
engine = sa.create_engine(url)
cnxn = engine.raw_connection().driver_connection
print(cnxn.character_set_name())  # utf8mb4
英文:

> what will the character set be? Will it be utf8mb4?

No, because you specify the equivalent of charset=utf8 in the connection URL and MySQL interprets that as utf8mb3

import sqlalchemy as sa

base_url = sa.URL.create(
    "mysql+mysqldb",
    username="scott",
    password="tiger",
    host="localhost",
    port=3307,
    database="test",
)

url = base_url.update_query_pairs([("charset", "utf8")])
engine = sa.create_engine(url)
cnxn = engine.raw_connection().driver_connection
print(cnxn.character_set_name())  # utf8mb3

Instead, use utf8mb4 specifically:

url = base_url.update_query_pairs([("charset", "utf8mb4")])
engine = sa.create_engine(url)
cnxn = engine.raw_connection().driver_connection
print(cnxn.character_set_name())  # utf8mb4

huangapple
  • 本文由 发表于 2023年5月11日 17:36:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76226185.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定