使用 SQLAlchemy 配置 connection_collation

Configure the connection_collation with SQLAlchemy

我正在尝试让 SQLAlchemy 连接到 MySQL,collation_connectionutf8mb4_unicode_ci

我的服务器和数据库都在使用 utf8mb4_unicode_ci 排序规则。在没有任何配置更改的情况下,我的 collation_connectionutf8_general_ci。如果我将连接字符串中的 charset 参数设置为 charset=utf8mb4,则 collation_connection 将设置为 utf8mb4_general_ci。我一直找不到任何说明如何在使用 SQLAlchemy 时设置 collation_connection 的文档。

这是一个特定于 mysql 的变量,您所能做的就是 运行 每个连接初始化的声明:

In [18]: url = 'mysql+pymysql://test:test@localhost/test'

In [19]: connect_args = {'init_command':"SET @@collation_connection='utf8mb4_unicode_ci'"}

In [20]: with sqlalchemy.create_engine(url, connect_args=connect_args).connect() as con:
    ...:     print(con.execute('select @@collation_connection;').fetchall())
    ...:
[('utf8mb4_unicode_ci',)]