英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论