MySQL 和 MariaDB

MySQL and MariaDB

Support for the MySQL / MariaDB database.

The following table summarizes current support levels for database release versions.

Supported MySQL / MariaDB versions

Support type

Versions

Supported version

5.6+ / 10+

Best effort

5.0.2+ / 5.0.2+

DBAPI Support

The following dialect/DBAPI options are available. Please refer to individual DBAPI sections for connect information.

支持的版本和功能

Supported Versions and Features

SQLAlchemy 支持从 MySQL 5.0.2 版本开始至今的现代版本,同时也支持所有现代版本的 MariaDB。关于各版本服务器所支持特性的详细信息,请参考官方 MySQL 文档。

在 1.4 版本发生变更: 最低支持的 MySQL 版本现为 5.0.2。

SQLAlchemy supports MySQL starting with version 5.0.2 through modern releases, as well as all modern versions of MariaDB. See the official MySQL documentation for detailed information about features supported in any given server release.

在 1.4 版本发生变更: minimum MySQL version supported is now 5.0.2.

MariaDB 支持

MariaDB Support

MariaDB 是 MySQL 的一个变种,其保留了与 MySQL 协议的基本兼容性,但这两个产品的开发正在逐渐分化。在 SQLAlchemy 中,这两个数据库之间存在少量语法和行为上的差异,SQLAlchemy 会自动处理这些差异。要连接 MariaDB 数据库,无需更改数据库 URL 格式:

engine = create_engine(
    "mysql+pymysql://user:pass@some_mariadb/dbname?charset=utf8mb4"
)

在首次连接时,SQLAlchemy 方言会执行一次服务器版本检测机制,用以识别所连接的数据库是否为 MariaDB。基于这一标志,方言会在需要作出行为差异处理的地方做出相应调整。

The MariaDB variant of MySQL retains fundamental compatibility with MySQL’s protocols however the development of these two products continues to diverge. Within the realm of SQLAlchemy, the two databases have a small number of syntactical and behavioral differences that SQLAlchemy accommodates automatically. To connect to a MariaDB database, no changes to the database URL are required:

engine = create_engine(
    "mysql+pymysql://user:pass@some_mariadb/dbname?charset=utf8mb4"
)

Upon first connect, the SQLAlchemy dialect employs a server version detection scheme that determines if the backing database reports as MariaDB. Based on this flag, the dialect can make different choices in those of areas where its behavior must be different.

MariaDB 专用模式

MariaDB-Only Mode

该方言还支持一个 可选的 MariaDB 专用连接模式,适用于某些依赖 MariaDB 特性、无法兼容 MySQL 的应用程序。若要启用此模式,只需将上述 URL 中的 “mysql” 替换为 “mariadb” 即可:

engine = create_engine(
    "mariadb+pymysql://user:pass@some_mariadb/dbname?charset=utf8mb4"
)

若在首次连接时检测到所连接的服务器不是 MariaDB,上述引擎将会抛出错误。

当使用 "mariadb" 作为方言名称时, 所有以 “mysql” 开头的方言选项必须改为使用 “mariadb” 开头。例如,选项 mysql_engine 应更名为 mariadb_engine,以此类推。对于同时使用 “mysql” 和 “mariadb” URL 的应用程序,两者的选项可同时指定:

my_table = Table(
    "mytable",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("textdata", String(50)),
    mariadb_engine="InnoDB",
    mysql_engine="InnoDB",
)

Index(
    "textdata_ix",
    my_table.c.textdata,
    mysql_prefix="FULLTEXT",
    mariadb_prefix="FULLTEXT",
)

当上述结构被反射时也会有类似行为,即当数据库 URL 以 “mariadb” 为前缀时,反射得到的选项也将以 “mariadb” 为前缀。

在 1.4 版本加入: 新增 “mariadb” 方言名称,用于支持 MySQL 方言下的 “MariaDB 专用模式”。

The dialect also supports an optional “MariaDB-only” mode of connection, which may be useful for the case where an application makes use of MariaDB-specific features and is not compatible with a MySQL database. To use this mode of operation, replace the “mysql” token in the above URL with “mariadb”:

engine = create_engine(
    "mariadb+pymysql://user:pass@some_mariadb/dbname?charset=utf8mb4"
)

The above engine, upon first connect, will raise an error if the server version detection detects that the backing database is not MariaDB.

When using an engine with "mariadb" as the dialect name, all mysql-specific options that include the name “mysql” in them are now named with “mariadb”. This means options like mysql_engine should be named mariadb_engine, etc. Both “mysql” and “mariadb” options can be used simultaneously for applications that use URLs with both “mysql” and “mariadb” dialects:

my_table = Table(
    "mytable",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("textdata", String(50)),
    mariadb_engine="InnoDB",
    mysql_engine="InnoDB",
)

Index(
    "textdata_ix",
    my_table.c.textdata,
    mysql_prefix="FULLTEXT",
    mariadb_prefix="FULLTEXT",
)

Similar behavior will occur when the above structures are reflected, i.e. the “mariadb” prefix will be present in the option names when the database URL is based on the “mariadb” name.

在 1.4 版本加入: Added “mariadb” dialect name supporting “MariaDB-only mode” for the MySQL dialect.

连接超时和断开连接

Connection Timeouts and Disconnects

MySQL / MariaDB 存在一个自动关闭空闲连接的行为,空闲时间达到固定时长(默认为 8 小时)后会自动断开。为避免该问题,可使用 create_engine.pool_recycle 选项,在连接池中某连接存活超过指定秒数后将其回收替换为新连接:

engine = create_engine("mysql+mysqldb://...", pool_recycle=3600)

若需更全面地检测连接中断(包括数据库重启、网络中断等),可采用预检测(pre-ping)方式。参见 处理断开连接 获取当前推荐方法。

参见

处理断开连接 — 关于连接超时及数据库重启的多种应对技术。

MySQL / MariaDB feature an automatic connection close behavior, for connections that have been idle for a fixed period of time, defaulting to eight hours. To circumvent having this issue, use the create_engine.pool_recycle option which ensures that a connection will be discarded and replaced with a new one if it has been present in the pool for a fixed number of seconds:

engine = create_engine("mysql+mysqldb://...", pool_recycle=3600)

For more comprehensive disconnect detection of pooled connections, including accommodation of server restarts and network issues, a pre-ping approach may be employed. See 处理断开连接 for current approaches.

参见

处理断开连接 - Background on several techniques for dealing with timed out connections as well as database restarts.

CREATE TABLE 参数(包括存储引擎)

CREATE TABLE arguments including Storage Engines

MySQL 和 MariaDB 的 CREATE TABLE 语法支持一系列特殊选项,如 ENGINECHARSETMAX_ROWSROW_FORMATINSERT_METHOD 等。为渲染这些选项,可使用 mysql_选项名="值" 的形式。例如,要创建一个表,使用 InnoDB 存储引擎,字符集为 utf8mb4,并设置 KEY_BLOCK_SIZE1024:

Table(
    "mytable",
    metadata,
    Column("data", String(32)),
    mysql_engine="InnoDB",
    mysql_charset="utf8mb4",
    mysql_key_block_size="1024",
)

若启用了 MariaDB 专用模式 模式,则也需使用带 “mariadb” 前缀的键名。各数据库的设置值当然可以不同,从而为 MySQL 与 MariaDB 分别保留不同设置:

# 同时支持 "mysql" 和 "mariadb-only" 引擎 URL

Table(
    "mytable",
    metadata,
    Column("data", String(32)),
    mysql_engine="InnoDB",
    mariadb_engine="InnoDB",
    mysql_charset="utf8mb4",
    mariadb_charset="utf8",
    mysql_key_block_size="1024",
    mariadb_key_block_size="1024",
)

MySQL / MariaDB 方言通常会将 mysql_关键字名 形式的参数转换为 CREATE TABLE 语句中的 KEYWORD_NAME 形式。部分选项名会在渲染时以空格而非下划线显示;对此 MySQL 方言会自动处理。这类特例包括 DATA DIRECTORY (对应 mysql_data_directory)、CHARACTER SET (对应 mysql_character_set)和 INDEX DIRECTORY (对应 mysql_index_directory)。

最常见的参数是 mysql_engine,用于指定表的存储引擎。历史上,MySQL 默认使用 MyISAM,而较新版本一般默认使用 InnoDB。通常推荐使用 InnoDB,因其支持事务和外键。

若使用 MyISAM 存储引擎在 MySQL / MariaDB 中创建 Table,该表将是非事务性的,所有对其的 INSERT/UPDATE/DELETE 操作都会自动提交。此外,它也不支持外键约束;尽管 CREATE TABLE 可接受外键选项,但在 MyISAM 下这些选项会被忽略。对这类表进行反射时也不会生成任何外键信息。

若要完整支持事务与外键约束,所有相关的 CREATE TABLE 语句必须指定一个支持事务的引擎,通常即为 InnoDB

分区功能也可以通过类似选项进行指定。例如,以下建表语句将设置 PARTITION_BYPARTITIONSSUBPARTITIONSSUBPARTITION_BY:

# 也可以使用 mariadb_* 前缀
Table(
    "testtable",
    MetaData(),
    Column("id", Integer(), primary_key=True, autoincrement=True),
    Column("other_id", Integer(), primary_key=True, autoincrement=False),
    mysql_partitions="2",
    mysql_partition_by="KEY(other_id)",
    mysql_subpartition_by="HASH(some_expr)",
    mysql_subpartitions="2",
)

渲染结果如下:

CREATE TABLE testtable (
        id INTEGER NOT NULL AUTO_INCREMENT,
        other_id INTEGER NOT NULL,
        PRIMARY KEY (id, other_id)
)PARTITION BY KEY(other_id) PARTITIONS 2 SUBPARTITION BY HASH(some_expr) SUBPARTITIONS 2

Both MySQL’s and MariaDB’s CREATE TABLE syntax includes a wide array of special options, including ENGINE, CHARSET, MAX_ROWS, ROW_FORMAT, INSERT_METHOD, and many more. To accommodate the rendering of these arguments, specify the form mysql_argument_name="value". For example, to specify a table with ENGINE of InnoDB, CHARSET of utf8mb4, and KEY_BLOCK_SIZE of 1024:

Table(
    "mytable",
    metadata,
    Column("data", String(32)),
    mysql_engine="InnoDB",
    mysql_charset="utf8mb4",
    mysql_key_block_size="1024",
)

When supporting MariaDB 专用模式 mode, similar keys against the “mariadb” prefix must be included as well. The values can of course vary independently so that different settings on MySQL vs. MariaDB may be maintained:

# support both "mysql" and "mariadb-only" engine URLs

Table(
    "mytable",
    metadata,
    Column("data", String(32)),
    mysql_engine="InnoDB",
    mariadb_engine="InnoDB",
    mysql_charset="utf8mb4",
    mariadb_charset="utf8",
    mysql_key_block_size="1024",
    mariadb_key_block_size="1024",
)

The MySQL / MariaDB dialects will normally transfer any keyword specified as mysql_keyword_name to be rendered as KEYWORD_NAME in the CREATE TABLE statement. A handful of these names will render with a space instead of an underscore; to support this, the MySQL dialect has awareness of these particular names, which include DATA DIRECTORY (e.g. mysql_data_directory), CHARACTER SET (e.g. mysql_character_set) and INDEX DIRECTORY (e.g. mysql_index_directory).

The most common argument is mysql_engine, which refers to the storage engine for the table. Historically, MySQL server installations would default to MyISAM for this value, although newer versions may be defaulting to InnoDB. The InnoDB engine is typically preferred for its support of transactions and foreign keys.

A Table that is created in a MySQL / MariaDB database with a storage engine of MyISAM will be essentially non-transactional, meaning any INSERT/UPDATE/DELETE statement referring to this table will be invoked as autocommit. It also will have no support for foreign key constraints; while the CREATE TABLE statement accepts foreign key options, when using the MyISAM storage engine these arguments are discarded. Reflecting such a table will also produce no foreign key constraint information.

For fully atomic transactions as well as support for foreign key constraints, all participating CREATE TABLE statements must specify a transactional engine, which in the vast majority of cases is InnoDB.

Partitioning can similarly be specified using similar options. In the example below the create table will specify PARTITION_BY, PARTITIONS, SUBPARTITIONS and SUBPARTITION_BY:

# can also use mariadb_* prefix
Table(
    "testtable",
    MetaData(),
    Column("id", Integer(), primary_key=True, autoincrement=True),
    Column("other_id", Integer(), primary_key=True, autoincrement=False),
    mysql_partitions="2",
    mysql_partition_by="KEY(other_id)",
    mysql_subpartition_by="HASH(some_expr)",
    mysql_subpartitions="2",
)

This will render:

CREATE TABLE testtable (
        id INTEGER NOT NULL AUTO_INCREMENT,
        other_id INTEGER NOT NULL,
        PRIMARY KEY (id, other_id)
)PARTITION BY KEY(other_id) PARTITIONS 2 SUBPARTITION BY HASH(some_expr) SUBPARTITIONS 2

大小写敏感和表反射

Case Sensitivity and Table Reflection

MySQL 和 MariaDB 对于区分大小写的标识符名称支持不一致,这种行为取决于底层操作系统的具体细节。然而已知的是,无论大小写敏感行为如何,在外键声明中表名总是 以全小写 形式从数据库中接收,因此无法准确地反射一个使用混合大小写标识符名称的表之间存在关系的模式。

因此,强烈建议在 SQLAlchemy 中以及 MySQL / MariaDB 数据库本身中都使用全小写的表名,特别是在使用数据库反射功能时尤为重要。

Both MySQL and MariaDB have inconsistent support for case-sensitive identifier names, basing support on specific details of the underlying operating system. However, it has been observed that no matter what case sensitivity behavior is present, the names of tables in foreign key declarations are always received from the database as all-lower case, making it impossible to accurately reflect a schema where inter-related tables use mixed-case identifier names.

Therefore it is strongly advised that table names be declared as all lower case both within SQLAlchemy as well as on the MySQL / MariaDB database itself, especially if database reflection features are to be used.

事务隔离级别

Transaction Isolation Level

所有 MySQL / MariaDB 方言都支持通过方言特定参数 create_engine.isolation_levelcreate_engine() 的参数设置事务隔离级别,同时也支持通过 Connection.execution_options.isolation_level 参数传递给 Connection.execution_options() 方法进行设置。 该功能通过在每个新连接上执行如下命令来实现:

SET SESSION TRANSACTION ISOLATION LEVEL <level>。对于特殊的 AUTOCOMMIT 隔离级别,则使用 DBAPI 特定的技术实现。

使用 create_engine() 设置隔离级别示例:

engine = create_engine(
    "mysql+mysqldb://scott:tiger@localhost/test",
    isolation_level="READ UNCOMMITTED",
)

使用连接执行选项设置隔离级别示例:

connection = engine.connect()
connection = connection.execution_options(isolation_level="READ COMMITTED")

isolation_level 参数支持的有效值包括:

  • READ COMMITTED

  • READ UNCOMMITTED

  • REPEATABLE READ

  • SERIALIZABLE

  • AUTOCOMMIT

特殊值 AUTOCOMMIT 会使用各个 DBAPI 提供的 “autocommit” 属性,目前支持 MySQLdb、MySQL-Client、MySQL-Connector Python 和 PyMySQL。使用该模式时,数据库连接会对如下语句返回 true:

SELECT @@autocommit;

此外,还可以通过创建与主 Engine 绑定的“子引擎”对象为每个连接配置不同的隔离级别设置。更多背景信息请参见 设置事务隔离级别(包括 DBAPI 自动提交) 部分。

All MySQL / MariaDB dialects support setting of transaction isolation level both via a dialect-specific parameter create_engine.isolation_level accepted by create_engine(), as well as the Connection.execution_options.isolation_level argument as passed to Connection.execution_options(). This feature works by issuing the command SET SESSION TRANSACTION ISOLATION LEVEL <level> for each new connection. For the special AUTOCOMMIT isolation level, DBAPI-specific techniques are used.

To set isolation level using create_engine():

engine = create_engine(
    "mysql+mysqldb://scott:tiger@localhost/test",
    isolation_level="READ UNCOMMITTED",
)

To set using per-connection execution options:

connection = engine.connect()
connection = connection.execution_options(isolation_level="READ COMMITTED")

Valid values for isolation_level include:

  • READ COMMITTED

  • READ UNCOMMITTED

  • REPEATABLE READ

  • SERIALIZABLE

  • AUTOCOMMIT

The special AUTOCOMMIT value makes use of the various “autocommit” attributes provided by specific DBAPIs, and is currently supported by MySQLdb, MySQL-Client, MySQL-Connector Python, and PyMySQL. Using it, the database connection will return true for the value of SELECT @@autocommit;.

There are also more options for isolation level configurations, such as “sub-engine” objects linked to a main Engine which each apply different isolation level settings. See the discussion at 设置事务隔离级别(包括 DBAPI 自动提交) for background.

AUTO_INCREMENT 行为

AUTO_INCREMENT Behavior

在创建表时,SQLAlchemy 会自动对第一个未标记为外键的 Integer 主键列设置 AUTO_INCREMENT:

>>> t = Table(
...     "mytable", metadata, Column("mytable_id", Integer, primary_key=True)
... )
>>> t.create()
CREATE TABLE mytable (
        id INTEGER NOT NULL AUTO_INCREMENT,
        PRIMARY KEY (id)
)

你可以通过向 Column 的参数 Column.autoincrement 传递 False 来禁用该行为。 此外,该标志也可用于在某些存储引擎中为多列主键中的次要列启用自动增长:

Table(
    "mytable",
    metadata,
    Column("gid", Integer, primary_key=True, autoincrement=False),
    Column("id", Integer, primary_key=True),
)

When creating tables, SQLAlchemy will automatically set AUTO_INCREMENT on the first Integer primary key column which is not marked as a foreign key:

>>> t = Table(
...     "mytable", metadata, Column("mytable_id", Integer, primary_key=True)
... )
>>> t.create()
CREATE TABLE mytable (
        id INTEGER NOT NULL AUTO_INCREMENT,
        PRIMARY KEY (id)
)

You can disable this behavior by passing False to the Column.autoincrement argument of Column. This flag can also be used to enable auto-increment on a secondary column in a multi-column key for some storage engines:

Table(
    "mytable",
    metadata,
    Column("gid", Integer, primary_key=True, autoincrement=False),
    Column("id", Integer, primary_key=True),
)

服务器端游标

Server Side Cursors

对于 mysqlclient、PyMySQL、mariadbconnector 等方言,支持服务端游标,其他方言也可能支持。该特性依赖于 DBAPI 中的 buffered=True/False 参数或使用类似 MySQLdb.cursors.SSCursorpymysql.cursors.SSCursor 的类进行内部处理。

服务端游标通过设置连接执行选项 Connection.execution_options.stream_results 来在每条语句上启用:

with engine.connect() as conn:
    result = conn.execution_options(stream_results=True).execute(
        text("select * from table")
    )

请注意,某些类型的 SQL 语句可能不支持服务端游标;一般来说,只应使用返回行结果的语句。

自 1.4 版本弃用.

方言级的 server_side_cursors 标志已被弃用,并将在未来版本中移除。请改用 Connection.stream_results 执行选项来实现非缓冲游标支持。

Server-side cursor support is available for the mysqlclient, PyMySQL, mariadbconnector dialects and may also be available in others. This makes use of either the “buffered=True/False” flag if available or by using a class such as MySQLdb.cursors.SSCursor or pymysql.cursors.SSCursor internally.

Server side cursors are enabled on a per-statement basis by using the Connection.execution_options.stream_results connection execution option:

with engine.connect() as conn:
    result = conn.execution_options(stream_results=True).execute(
        text("select * from table")
    )

Note that some kinds of SQL statements may not be supported with server side cursors; generally, only SQL statements that return rows should be used with this option.

自 1.4 版本弃用: The dialect-level server_side_cursors flag is deprecated and will be removed in a future release. Please use the Connection.stream_results execution option for unbuffered cursor support.

Unicode

字符集选择

Charset Selection

大多数 MySQL / MariaDB 的 DBAPI 驱动程序都提供了设置连接的客户端字符集的选项。通常可以通过 URL 中的 charset 参数进行设置,例如:

e = create_engine(
    "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4"
)

该字符集是该连接的 客户端字符集 。某些 MySQL 的 DBAPI 默认使用 latin1,而有些则使用 my.cnf 文件中的 default-character-set 设置。关于具体行为,请查阅所使用的 DBAPI 的文档。

用于 Unicode 的编码传统上为 'utf8'。然而,从 MySQL 5.5.3 和 MariaDB 5.5 开始,引入了一个新的 MySQL 特有编码 'utf8mb4';并且从 MySQL 8.0 起,如果在服务器端配置中指定了普通的 utf8,服务器将发出警告,并用 utf8mb3 取而代之。之所以引入该编码,是因为 MySQL 的传统 utf-8 编码仅支持最多三字节的码位,而非四字节。因此,在与包含四字节以上码位的 MySQL 或 MariaDB 数据库通信时,若数据库和客户端 DBAPI 都支持,推荐使用此新字符集,例如:

e = create_engine(
    "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4"
)

所有现代 DBAPI 都应支持 utf8mb4 字符集。

若想在使用旧版 utf8 创建的数据库结构中使用 utf8mb4 编码,可能需要修改 MySQL / MariaDB 的模式定义或服务器配置。

参见

The utf8mb4 Character Set - 来自 MySQL 官方文档

Most MySQL / MariaDB DBAPIs offer the option to set the client character set for a connection. This is typically delivered using the charset parameter in the URL, such as:

e = create_engine(
    "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4"
)

This charset is the client character set for the connection. Some MySQL DBAPIs will default this to a value such as latin1, and some will make use of the default-character-set setting in the my.cnf file as well. Documentation for the DBAPI in use should be consulted for specific behavior.

The encoding used for Unicode has traditionally been 'utf8'. However, for MySQL versions 5.5.3 and MariaDB 5.5 on forward, a new MySQL-specific encoding 'utf8mb4' has been introduced, and as of MySQL 8.0 a warning is emitted by the server if plain utf8 is specified within any server-side directives, replaced with utf8mb3. The rationale for this new encoding is due to the fact that MySQL’s legacy utf-8 encoding only supports codepoints up to three bytes instead of four. Therefore, when communicating with a MySQL or MariaDB database that includes codepoints more than three bytes in size, this new charset is preferred, if supported by both the database as well as the client DBAPI, as in:

e = create_engine(
    "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4"
)

All modern DBAPIs should support the utf8mb4 charset.

In order to use utf8mb4 encoding for a schema that was created with legacy utf8, changes to the MySQL/MariaDB schema and/or server configuration may be required.

参见

The utf8mb4 Character Set - in the MySQL documentation

处理二进制数据警告和 Unicode

Dealing with Binary Data Warnings and Unicode

MySQL 从 5.6、5.7 起(撰写本文时 MariaDB 尚未支持)在以下情况下会发出警告:即当已设置字符编码时,将二进制数据传递给数据库,而该二进制数据并不符合该编码的格式:

default.py:509: Warning: (1300, "Invalid utf8mb4 character string:
'F9876A'")
cursor.execute(statement, parameters)

该警告是由于 MySQL 客户端库试图将二进制字符串解释为 Unicode 对象,即使正在使用的数据类型是 LargeBinary。为了解决该问题,SQL 语句中必须为非 NULL 值添加一个二进制“字符集前缀”,如下所示:

INSERT INTO table (data) VALUES (_binary %s)

该字符集前缀由 DBAPI 驱动程序提供支持,前提是使用了 mysqlclient 或 PyMySQL(推荐这两个驱动)。可通过在 URL 中添加 binary_prefix=true 查询参数来解决该警告:

# mysqlclient
engine = create_engine(
    "mysql+mysqldb://scott:tiger@localhost/test?charset=utf8mb4&binary_prefix=true"
)

# PyMySQL
engine = create_engine(
    "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4&binary_prefix=true"
)

其他 MySQL 驱动程序可能支持或不支持 binary_prefix 标志。

SQLAlchemy 本身无法可靠地生成该 _binary 前缀,因为它不适用于 NULL 值,而 NULL 值作为绑定参数是合法的。由于 MySQL 驱动程序会将参数直接渲染进 SQL 字符串中,这是添加该关键字最有效的位置。

参见

Character set introducers - MySQL 官方网站

MySQL versions 5.6, 5.7 and later (not MariaDB at the time of this writing) now emit a warning when attempting to pass binary data to the database, while a character set encoding is also in place, when the binary data itself is not valid for that encoding:

default.py:509: Warning: (1300, "Invalid utf8mb4 character string:
'F9876A'")
cursor.execute(statement, parameters)

This warning is due to the fact that the MySQL client library is attempting to interpret the binary string as a unicode object even if a datatype such as LargeBinary is in use. To resolve this, the SQL statement requires a binary “character set introducer” be present before any non-NULL value that renders like this:

INSERT INTO table (data) VALUES (_binary %s)

These character set introducers are provided by the DBAPI driver, assuming the use of mysqlclient or PyMySQL (both of which are recommended). Add the query string parameter binary_prefix=true to the URL to repair this warning:

# mysqlclient
engine = create_engine(
    "mysql+mysqldb://scott:tiger@localhost/test?charset=utf8mb4&binary_prefix=true"
)

# PyMySQL
engine = create_engine(
    "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4&binary_prefix=true"
)

The binary_prefix flag may or may not be supported by other MySQL drivers.

SQLAlchemy itself cannot render this _binary prefix reliably, as it does not work with the NULL value, which is valid to be sent as a bound parameter. As the MySQL driver renders parameters directly into the SQL string, it’s the most efficient place for this additional keyword to be passed.

参见

Character set introducers - on the MySQL website

ANSI 引用样式

ANSI Quoting Style

MySQL / MariaDB 支持两种标识符“引用风格”:一种使用反引号(backticks),另一种使用引号,例如:`some_identifier`"some_identifier"。所有 MySQL 方言在首次与特定 Engine 建立连接时会检查 sql_mode 的值来自动检测所使用的引用风格。

MySQL / MariaDB feature two varieties of identifier “quoting style”, one using backticks and the other using quotes, e.g. `some_identifier` vs. "some_identifier". All MySQL dialects detect which version is in use by checking the value of sql_mode when a connection is first established with a particular Engine. This quoting style comes into play when rendering table and column names as well as when reflecting existing database structures. The detection is entirely automatic and no special configuration is needed to use either quoting style.

更改 sql_mode

Changing the sql_mode

引用风格会影响表名、列名的渲染,以及对已有数据库结构的反射。该检测过程是完全自动的,无需任何额外配置即可使用任一引用风格。

MySQL 支持在多个 服务器 SQL 模式 下运行,适用于服务器和客户端。要为某个应用程序更改 sql_mode,开发者可以利用 SQLAlchemy 的事件系统(Events system)。

在以下示例中,通过事件系统在 first_connectconnect 事件中设置 sql_mode:

from sqlalchemy import create_engine, event

eng = create_engine(
    "mysql+mysqldb://scott:tiger@localhost/test", echo="debug"
)


# `insert=True` 确保该监听器最先运行
@event.listens_for(eng, "connect", insert=True)
def connect(dbapi_connection, connection_record):
    cursor = dbapi_connection.cursor()
    cursor.execute("SET sql_mode = 'STRICT_ALL_TABLES'")


conn = eng.connect()

在上述示例中, “connect” 事件会在为某个连接池首次创建 DBAPI 连接时执行该 SET 语句,此时连接尚未进入连接池可用状态。此外,由于注册事件处理函数时使用了 insert=True,它会被添加到注册函数列表的最前面。

MySQL supports operating in multiple Server SQL Modes for both Servers and Clients. To change the sql_mode for a given application, a developer can leverage SQLAlchemy’s Events system.

In the following example, the event system is used to set the sql_mode on the first_connect and connect events:

from sqlalchemy import create_engine, event

eng = create_engine(
    "mysql+mysqldb://scott:tiger@localhost/test", echo="debug"
)


# `insert=True` will ensure this is the very first listener to run
@event.listens_for(eng, "connect", insert=True)
def connect(dbapi_connection, connection_record):
    cursor = dbapi_connection.cursor()
    cursor.execute("SET sql_mode = 'STRICT_ALL_TABLES'")


conn = eng.connect()

In the example illustrated above, the “connect” event will invoke the “SET” statement on the connection at the moment a particular DBAPI connection is first created for a given Pool, before the connection is made available to the connection pool. Additionally, because the function was registered with insert=True, it will be prepended to the internal list of registered functions.

MySQL / MariaDB SQL 扩展

MySQL / MariaDB SQL Extensions

许多 MySQL / MariaDB 的 SQL 扩展通过 SQLAlchemy 的通用函数和操作符支持得以实现,例如:

table.select(table.c.password == func.md5("plaintext"))
table.select(table.c.username.op("regexp")("^[a-d]"))

当然,也可以直接执行任意合法的 SQL 字符串语句。

目前对 MySQL / MariaDB SQL 扩展的一些有限直接支持如下:

  • INSERT..ON DUPLICATE KEY UPDATE:参见 INSERT…ON DUPLICATE KEY UPDATE(更新插入)

  • SELECT 语句前缀,使用 Select.prefix_with()Query.prefix_with():

    select(...).prefix_with(["HIGH_PRIORITY", "SQL_SMALL_RESULT"])
  • UPDATE 限制行数:

    from sqlalchemy.dialects.mysql import limit
    
    update(...).ext(limit(10))

    在 2.1 版本发生变更: 改为使用 limit() 扩展,替代先前的 mysql_limit 使用方式

  • DELETE 限制行数:

    from sqlalchemy.dialects.mysql import limit
    
    delete(...).ext(limit(10))

    在 2.1 版本发生变更: 改为使用 limit() 扩展,替代先前的 mysql_limit 使用方式

  • 优化器提示,使用 Select.prefix_with()Query.prefix_with():

    select(...).prefix_with("/*+ NO_RANGE_OPTIMIZATION(t4 PRIMARY) */")
  • 索引提示,使用 Select.with_hint()Query.with_hint():

    select(...).with_hint(some_table, "USE INDEX xyz")
  • MATCH 操作符支持:

    from sqlalchemy.dialects.mysql import match
    
    select(...).where(match(col1, col2, against="some expr").in_boolean_mode())

    参见

    match

Many of the MySQL / MariaDB SQL extensions are handled through SQLAlchemy’s generic function and operator support:

table.select(table.c.password == func.md5("plaintext"))
table.select(table.c.username.op("regexp")("^[a-d]"))

And of course any valid SQL statement can be executed as a string as well.

Some limited direct support for MySQL / MariaDB extensions to SQL is currently available.

  • INSERT..ON DUPLICATE KEY UPDATE: See INSERT…ON DUPLICATE KEY UPDATE(更新插入)

  • SELECT pragma, use Select.prefix_with() and Query.prefix_with():

    select(...).prefix_with(["HIGH_PRIORITY", "SQL_SMALL_RESULT"])
  • UPDATE with LIMIT:

    from sqlalchemy.dialects.mysql import limit
    
    update(...).ext(limit(10))

    在 2.1 版本发生变更: the limit() extension supersedes the previous use of mysql_limit

  • DELETE with LIMIT:

    from sqlalchemy.dialects.mysql import limit
    
    delete(...).ext(limit(10))

    在 2.1 版本发生变更: the limit() extension supersedes the previous use of mysql_limit

  • optimizer hints, use Select.prefix_with() and Query.prefix_with():

    select(...).prefix_with("/*+ NO_RANGE_OPTIMIZATION(t4 PRIMARY) */")
  • index hints, use Select.with_hint() and Query.with_hint():

    select(...).with_hint(some_table, "USE INDEX xyz")
  • MATCH operator support:

    from sqlalchemy.dialects.mysql import match
    
    select(...).where(match(col1, col2, against="some expr").in_boolean_mode())

    参见

    match

INSERT/DELETE…RETURNING

INSERT/DELETE…RETURNING

MariaDB dialect 支持 10.5+ 的 INSERT..RETURNING 和 10.0+ 的 DELETE..RETURNING 语法。INSERT..RETURNING 在某些情况下会被自动使用,以获取新生成的标识符,替代传统的 cursor.lastrowid 方法。然而,对于简单的单语句操作,目前仍首选使用 cursor.lastrowid,因其性能更优。

要显式指定 RETURNING 子句,可在每条语句上使用 _UpdateBase.returning() 方法:

# INSERT..RETURNING
result = connection.execute(
    table.insert().values(name="foo").returning(table.c.col1, table.c.col2)
)
print(result.all())

# DELETE..RETURNING
result = connection.execute(
    table.delete()
    .where(table.c.name == "foo")
    .returning(table.c.col1, table.c.col2)
)
print(result.all())

在 2.0 版本加入: 增加对 MariaDB RETURNING 的支持

The MariaDB dialect supports 10.5+’s INSERT..RETURNING and DELETE..RETURNING (10.0+) syntaxes. INSERT..RETURNING may be used automatically in some cases in order to fetch newly generated identifiers in place of the traditional approach of using cursor.lastrowid, however cursor.lastrowid is currently still preferred for simple single-statement cases for its better performance.

To specify an explicit RETURNING clause, use the _UpdateBase.returning() method on a per-statement basis:

# INSERT..RETURNING
result = connection.execute(
    table.insert().values(name="foo").returning(table.c.col1, table.c.col2)
)
print(result.all())

# DELETE..RETURNING
result = connection.execute(
    table.delete()
    .where(table.c.name == "foo")
    .returning(table.c.col1, table.c.col2)
)
print(result.all())

在 2.0 版本加入: Added support for MariaDB RETURNING

INSERT…ON DUPLICATE KEY UPDATE(更新插入)

INSERT…ON DUPLICATE KEY UPDATE (Upsert)

MySQL / MariaDB 支持通过 INSERT 语句中的 ON DUPLICATE KEY UPDATE 子句对表中的行执行“插入或更新”(upsert)操作。仅当候选行与表中现有的主键或唯一键不匹配时才会插入该行;否则会执行 UPDATE 操作。该语句支持分别指定 INSERT 和 UPDATE 的值。

SQLAlchemy 通过 MySQL 专属的 insert() 函数支持 ON DUPLICATE KEY UPDATE,该函数提供生成式方法 Insert.on_duplicate_key_update()

>>> from sqlalchemy.dialects.mysql import insert

>>> insert_stmt = insert(my_table).values(
...     id="some_existing_id", data="inserted value"
... )

>>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
...     data=insert_stmt.inserted.data, status="U"
... )
>>> print(on_duplicate_key_stmt)
INSERT INTO my_table (id, data) VALUES (%s, %s) ON DUPLICATE KEY UPDATE data = VALUES(data), status = %s

与 PostgreSQL 的 “ON CONFLICT” 子句不同,”ON DUPLICATE KEY UPDATE” 总是匹配任意主键或唯一键,若匹配成功总是执行 UPDATE;无法选择报错或跳过更新。

ON DUPLICATE KEY UPDATE 可对已存在行执行更新操作,更新值可来自插入的新值,也可自定义指定。这些值通常以关键字参数形式传递给 Insert.on_duplicate_key_update(),其中键为列的 key(通常即列名,除非设置了 Column.key),值为字面量或 SQL 表达式:

>>> insert_stmt = insert(my_table).values(
...     id="some_existing_id", data="inserted value"
... )

>>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
...     data="some data",
...     updated_at=func.current_timestamp(),
... )

>>> print(on_duplicate_key_stmt)
INSERT INTO my_table (id, data) VALUES (%s, %s) ON DUPLICATE KEY UPDATE data = %s, updated_at = CURRENT_TIMESTAMP

类似于 UpdateBase.values() 的用法,也可以使用其他参数形式,包括字典:

>>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
...     {"data": "some data", "updated_at": func.current_timestamp()},
... )

还可以使用 2 元组组成的列表,这种方式会自动生成一个按照参数顺序排列的 UPDATE 语句,类似于 参数有序更新 中描述的方式。与 Update 对象不同,在这种上下文中无需特殊标志标明意图,因为其形式明确:

>>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
...     [
...         ("data", "some data"),
...         ("updated_at", func.current_timestamp()),
...     ]
... )

>>> print(on_duplicate_key_stmt)
INSERT INTO my_table (id, data) VALUES (%s, %s) ON DUPLICATE KEY UPDATE data = %s, updated_at = CURRENT_TIMESTAMP

警告

Insert.on_duplicate_key_update() 方法 不会 考虑 Python 端定义的默认 UPDATE 值或生成函数, 例如通过 Column.onupdate 指定的值。除非显式指定,这些值不会在 ON DUPLICATE KEY 类型的 UPDATE 中起作用。

为了引用即将插入的行,可以使用特殊别名 Insert.inserted,它是 Insert 对象上的一个属性;该对象是一个 ColumnCollection,包含目标表的所有列:

>>> stmt = insert(my_table).values(
...     id="some_id", data="inserted value", author="jlh"
... )

>>> do_update_stmt = stmt.on_duplicate_key_update(
...     data="updated value", author=stmt.inserted.author
... )

>>> print(do_update_stmt)
INSERT INTO my_table (id, data, author) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE data = %s, author = VALUES(author)

渲染时,“inserted” 命名空间将生成 VALUES(<columnname>) 表达式。

MySQL / MariaDB allow “upserts” (update or insert) of rows into a table via the ON DUPLICATE KEY UPDATE clause of the INSERT statement. A candidate row will only be inserted if that row does not match an existing primary or unique key in the table; otherwise, an UPDATE will be performed. The statement allows for separate specification of the values to INSERT versus the values for UPDATE.

SQLAlchemy provides ON DUPLICATE KEY UPDATE support via the MySQL-specific insert() function, which provides the generative method Insert.on_duplicate_key_update():

>>> from sqlalchemy.dialects.mysql import insert

>>> insert_stmt = insert(my_table).values(
...     id="some_existing_id", data="inserted value"
... )

>>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
...     data=insert_stmt.inserted.data, status="U"
... )
>>> print(on_duplicate_key_stmt)
INSERT INTO my_table (id, data) VALUES (%s, %s) ON DUPLICATE KEY UPDATE data = VALUES(data), status = %s

Unlike PostgreSQL’s “ON CONFLICT” phrase, the “ON DUPLICATE KEY UPDATE” phrase will always match on any primary key or unique key, and will always perform an UPDATE if there’s a match; there are no options for it to raise an error or to skip performing an UPDATE.

ON DUPLICATE KEY UPDATE is used to perform an update of the already existing row, using any combination of new values as well as values from the proposed insertion. These values are normally specified using keyword arguments passed to the Insert.on_duplicate_key_update() given column key values (usually the name of the column, unless it specifies Column.key ) as keys and literal or SQL expressions as values:

>>> insert_stmt = insert(my_table).values(
...     id="some_existing_id", data="inserted value"
... )

>>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
...     data="some data",
...     updated_at=func.current_timestamp(),
... )

>>> print(on_duplicate_key_stmt)
INSERT INTO my_table (id, data) VALUES (%s, %s) ON DUPLICATE KEY UPDATE data = %s, updated_at = CURRENT_TIMESTAMP

In a manner similar to that of UpdateBase.values(), other parameter forms are accepted, including a single dictionary:

>>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
...     {"data": "some data", "updated_at": func.current_timestamp()},
... )

as well as a list of 2-tuples, which will automatically provide a parameter-ordered UPDATE statement in a manner similar to that described at 参数有序更新. Unlike the Update object, no special flag is needed to specify the intent since the argument form is this context is unambiguous:

>>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
...     [
...         ("data", "some data"),
...         ("updated_at", func.current_timestamp()),
...     ]
... )

>>> print(on_duplicate_key_stmt)
INSERT INTO my_table (id, data) VALUES (%s, %s) ON DUPLICATE KEY UPDATE data = %s, updated_at = CURRENT_TIMESTAMP

警告

The Insert.on_duplicate_key_update() method does not take into account Python-side default UPDATE values or generation functions, e.g. e.g. those specified using Column.onupdate. These values will not be exercised for an ON DUPLICATE KEY style of UPDATE, unless they are manually specified explicitly in the parameters.

In order to refer to the proposed insertion row, the special alias Insert.inserted is available as an attribute on the Insert object; this object is a ColumnCollection which contains all columns of the target table:

>>> stmt = insert(my_table).values(
...     id="some_id", data="inserted value", author="jlh"
... )

>>> do_update_stmt = stmt.on_duplicate_key_update(
...     data="updated value", author=stmt.inserted.author
... )

>>> print(do_update_stmt)
INSERT INTO my_table (id, data, author) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE data = %s, author = VALUES(author)

When rendered, the “inserted” namespace will produce the expression VALUES(<columnname>).

行数支持

rowcount Support

SQLAlchemy 对 DBAPI 的 cursor.rowcount 属性进行了标准化处理,其语义被统一为“UPDATE 或 DELETE 语句所匹配的行数”。 这一行为与大多数 MySQL DBAPI 驱动的默认设置相反,后者通常返回“实际被修改或删除的行数”。 因此,SQLAlchemy 的 MySQL 方言在建立连接时总是添加 constants.CLIENT.FOUND_ROWS 标志,或者目标方言等效的设置。 这一配置当前是硬编码实现的。

SQLAlchemy standardizes the DBAPI cursor.rowcount attribute to be the usual definition of “number of rows matched by an UPDATE or DELETE” statement. This is in contradiction to the default setting on most MySQL DBAPI drivers, which is “number of rows actually modified/deleted”. For this reason, the SQLAlchemy MySQL dialects always add the constants.CLIENT.FOUND_ROWS flag, or whatever is equivalent for the target dialect, upon connection. This setting is currently hardcoded.

MySQL / MariaDB 特定索引选项

MySQL / MariaDB- Specific Index Options

MySQL 和 MariaDB 为 Index 构造器提供了特定的扩展。

MySQL and MariaDB-specific extensions to the Index construct are available.

索引长度

Index Length

MySQL 和 MariaDB 都支持在创建索引时为每个索引列指定一个“长度”(length)参数, 该参数表示每个索引值中被用于建立索引的字符或字节数。 SQLAlchemy 通过 mysql_length 和/或 mariadb_length 参数提供此功能:

Index("my_index", my_table.c.data, mysql_length=10, mariadb_length=10)

Index("a_b_idx", my_table.c.a, my_table.c.b, mysql_length={"a": 4, "b": 9})

Index(
    "a_b_idx", my_table.c.a, my_table.c.b, mariadb_length={"a": 4, "b": 9}
)

对于非二进制字符串类型,该前缀长度以“字符数”为单位;而对于二进制字符串类型,则以“字节数”为单位。 传入该关键字参数的值必须是一个整数(表示为索引中所有列统一设定前缀长度), 或是一个字典,其中键为列名,值为相应列的前缀长度。

MySQL and MariaDB both provide an option to create index entries with a certain length, where “length” refers to the number of characters or bytes in each value which will become part of the index. SQLAlchemy provides this feature via the mysql_length and/or mariadb_length parameters:

Index("my_index", my_table.c.data, mysql_length=10, mariadb_length=10)

Index("a_b_idx", my_table.c.a, my_table.c.b, mysql_length={"a": 4, "b": 9})

Index(
    "a_b_idx", my_table.c.a, my_table.c.b, mariadb_length={"a": 4, "b": 9}
)

Prefix lengths are given in characters for nonbinary string types and in bytes for binary string types. The value passed to the keyword argument must be either an integer (and, thus, specify the same prefix length value for all columns of the index) or a dict in which keys are column names and values are prefix length values for corresponding columns. MySQL and MariaDB only allow a length for a column of an index if it is for a CHAR, VARCHAR, TEXT, BINARY, VARBINARY and BLOB.

索引前缀

Index Prefixes

MySQL 和 MariaDB 仅允许在索引中指定 CHAR、VARCHAR、TEXT、BINARY、VARBINARY 和 BLOB 类型的列的长度。

MySQL 存储引擎支持在创建索引时指定索引前缀。SQLAlchemy 提供了 mysql_prefix 参数用于 Index

Index("my_index", my_table.c.data, mysql_prefix="FULLTEXT")

该参数的值将原样传递给底层的 CREATE INDEX 语句,因此必须是你所使用的 MySQL 存储引擎支持的有效前缀关键字。

参见

CREATE INDEX - MySQL 官方文档

MySQL storage engines permit you to specify an index prefix when creating an index. SQLAlchemy provides this feature via the mysql_prefix parameter on Index:

Index("my_index", my_table.c.data, mysql_prefix="FULLTEXT")

The value passed to the keyword argument will be simply passed through to the underlying CREATE INDEX, so it must be a valid index prefix for your MySQL storage engine.

参见

CREATE INDEX - MySQL documentation

索引类型

Index Types

某些 MySQL 存储引擎还允许在创建索引或主键约束时指定索引类型。 SQLAlchemy 提供了 mysql_using 参数用于 Index

Index(
    "my_index", my_table.c.data, mysql_using="hash", mariadb_using="hash"
)

也可以在 PrimaryKeyConstraint 上使用 mysql_using 参数:

PrimaryKeyConstraint("data", mysql_using="hash", mariadb_using="hash")

该参数的值将被原样传递给 CREATE INDEX 或 PRIMARY KEY 子句, 因此必须是你使用的 MySQL 存储引擎支持的有效索引类型。

更多信息请参考:

https://dev.mysql.com/doc/refman/5.0/en/create-index.html https://dev.mysql.com/doc/refman/5.0/en/create-table.html

Some MySQL storage engines permit you to specify an index type when creating an index or primary key constraint. SQLAlchemy provides this feature via the mysql_using parameter on Index:

Index(
    "my_index", my_table.c.data, mysql_using="hash", mariadb_using="hash"
)

As well as the mysql_using parameter on PrimaryKeyConstraint:

PrimaryKeyConstraint("data", mysql_using="hash", mariadb_using="hash")

The value passed to the keyword argument will be simply passed through to the underlying CREATE INDEX or PRIMARY KEY clause, so it must be a valid index type for your MySQL storage engine.

More information can be found at:

https://dev.mysql.com/doc/refman/5.0/en/create-index.html

https://dev.mysql.com/doc/refman/5.0/en/create-table.html

索引解析器

Index Parsers

MySQL 中的 CREATE FULLTEXT INDEX 还支持 “WITH PARSER” 选项。 此功能可通过 mysql_with_parser 关键字参数实现:

Index(
    "my_index",
    my_table.c.data,
    mysql_prefix="FULLTEXT",
    mysql_with_parser="ngram",
    mariadb_prefix="FULLTEXT",
    mariadb_with_parser="ngram",
)

CREATE FULLTEXT INDEX in MySQL also supports a “WITH PARSER” option. This is available using the keyword argument mysql_with_parser:

Index(
    "my_index",
    my_table.c.data,
    mysql_prefix="FULLTEXT",
    mysql_with_parser="ngram",
    mariadb_prefix="FULLTEXT",
    mariadb_with_parser="ngram",
)

MySQL / MariaDB 外键

MySQL / MariaDB Foreign Keys

MySQL 和 MariaDB 关于外键的行为有一些重要的警告。

MySQL and MariaDB’s behavior regarding foreign keys has some important caveats.

应避免使用的外键参数

Foreign Key Arguments to Avoid

MySQL 和 MariaDB 均不支持外键参数 “DEFERRABLE”、”INITIALLY” 或 “MATCH”。 在 ForeignKeyConstraintForeignKey 中使用 deferrableinitially 关键字参数,会导致这些关键字出现在生成的 DDL 表达式中,从而在 MySQL 或 MariaDB 上引发错误。 若希望在外键中使用这些关键字但又希望在 MySQL / MariaDB 后端中忽略它们,可使用自定义编译规则实现:

from sqlalchemy.ext.compiler import compiles
from sqlalchemy.schema import ForeignKeyConstraint

@compiles(ForeignKeyConstraint, "mysql", "mariadb")
def process(element, compiler, **kw):
    element.deferrable = element.initially = None
    return compiler.visit_foreign_key_constraint(element, **kw)

“ MATCH “ 关键字则更为棘手,SQLAlchemy 明确禁止其与 MySQL 或 MariaDB 后端同时使用。 虽然 MySQL / MariaDB 会静默忽略该参数,但其副作用是导致 ON UPDATE 和 ON DELETE 选项也被后端忽略。 因此,在 MySQL / MariaDB 后端中 绝不可使用 MATCH;如同 DEFERRABLE 和 INITIALLY,可使用自定义编译规则在定义 DDL 时修正 ForeignKeyConstraint。

Neither MySQL nor MariaDB support the foreign key arguments “DEFERRABLE”, “INITIALLY”, or “MATCH”. Using the deferrable or initially keyword argument with ForeignKeyConstraint or ForeignKey will have the effect of these keywords being rendered in a DDL expression, which will then raise an error on MySQL or MariaDB. In order to use these keywords on a foreign key while having them ignored on a MySQL / MariaDB backend, use a custom compile rule:

from sqlalchemy.ext.compiler import compiles
from sqlalchemy.schema import ForeignKeyConstraint


@compiles(ForeignKeyConstraint, "mysql", "mariadb")
def process(element, compiler, **kw):
    element.deferrable = element.initially = None
    return compiler.visit_foreign_key_constraint(element, **kw)

The “MATCH” keyword is in fact more insidious, and is explicitly disallowed by SQLAlchemy in conjunction with the MySQL or MariaDB backends. This argument is silently ignored by MySQL / MariaDB, but in addition has the effect of ON UPDATE and ON DELETE options also being ignored by the backend. Therefore MATCH should never be used with the MySQL / MariaDB backends; as is the case with DEFERRABLE and INITIALLY, custom compilation rules can be used to correct a ForeignKeyConstraint at DDL definition time.

外键约束的反射

Reflection of Foreign Key Constraints

并非所有 MySQL / MariaDB 存储引擎都支持外键。若使用常见的 MyISAM 存储引擎,通过表反射机制加载的信息将 不包含外键信息。对于此类表,您可以在反射时显式提供 ForeignKeyConstraint:

Table(

“mytable”, metadata, ForeignKeyConstraint([“other_id”], [“othertable.other_id”]), autoload_with=engine,

)

Not all MySQL / MariaDB storage engines support foreign keys. When using the very common MyISAM MySQL storage engine, the information loaded by table reflection will not include foreign keys. For these tables, you may supply a ForeignKeyConstraint at reflection time:

Table(

“mytable”, metadata, ForeignKeyConstraint([“other_id”], [“othertable.other_id”]), autoload_with=engine,

)

MySQL / MariaDB 唯一约束和反射

MySQL / MariaDB Unique Constraints and Reflection

SQLAlchemy 支持使用 unique=True 标志的 Index 构造,用于表示唯一索引,以及 UniqueConstraint 构造,用于表示唯一约束。 在发出用于创建这些约束的 DDL 时,MySQL / MariaDB 同时支持这两种对象/语法。 然而,MySQL / MariaDB 并不存在与唯一索引分离的唯一约束结构;也就是说,在 MySQL / MariaDB 中的 “UNIQUE” 约束等同于创建 “UNIQUE INDEX”。

在反射这些结构时,Inspector.get_indexes()Inspector.get_unique_constraints() 方法 会返回 MySQL / MariaDB 中的唯一索引条目。 但在使用 Table(..., autoload_with=engine) 进行完整表反射时,UniqueConstraint 构造 不会 出现在任何情况下反射得到的 Table 构造中;此构造总是由 unique=True 标志的 Index 表示,并包含在 Table.indexes 集合中。

SQLAlchemy supports both the Index construct with the flag unique=True, indicating a UNIQUE index, as well as the UniqueConstraint construct, representing a UNIQUE constraint. Both objects/syntaxes are supported by MySQL / MariaDB when emitting DDL to create these constraints. However, MySQL / MariaDB does not have a unique constraint construct that is separate from a unique index; that is, the “UNIQUE” constraint on MySQL / MariaDB is equivalent to creating a “UNIQUE INDEX”.

When reflecting these constructs, the Inspector.get_indexes() and the Inspector.get_unique_constraints() methods will both return an entry for a UNIQUE index in MySQL / MariaDB. However, when performing full table reflection using Table(..., autoload_with=engine), the UniqueConstraint construct is not part of the fully reflected Table construct under any circumstances; this construct is always represented by a Index with the unique=True setting present in the Table.indexes collection.

TIMESTAMP / DATETIME 问题

TIMESTAMP / DATETIME issues

MySQL/MariaDB 的 explicit_defaults_for_timestamp 在更新当前时间戳时渲染

Rendering ON UPDATE CURRENT TIMESTAMP for MySQL / MariaDB’s explicit_defaults_for_timestamp

MySQL / MariaDB 历来会将 TIMESTAMP 数据类型的 DDL 扩展为 “TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP”, 其中包含非标准 SQL 语法,使列在 UPDATE 操作时自动更新为当前时间戳,从而省去了使用触发器实现服务端更新的需求。

MySQL 5.6 引入了一个新标志 explicit_defaults_for_timestamp, 用于禁用上述行为;在 MySQL 8 中,该标志默认开启。 因此,为了在不更改该标志的前提下启用 MySQL 的 “on update timestamp” 行为,必须显式生成上述 DDL。 此外,对于 DATETIME 类型也同样适用。

SQLAlchemy 的 MySQL 方言目前尚未提供用于生成 MySQL 的 “ON UPDATE CURRENT_TIMESTAMP” 子句的选项; 需要注意的是,这并非通用的 “ON UPDATE” 功能,因为标准 SQL 中并无此类语法。 SQLAlchemy 的 Column.server_onupdate 参数当前与 MySQL 特有的行为无关。

若要生成该 DDL,可使用 Column.server_default 参数,并传入包含 ON UPDATE 子句的文本表达式:

from sqlalchemy import Table, MetaData, Column, Integer, String, TIMESTAMP
from sqlalchemy import text

metadata = MetaData()

mytable = Table(
    "mytable",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("data", String(50)),
    Column(
        "last_updated",
        TIMESTAMP,
        server_default=text(
            "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
        ),
    ),
)

对于 DateTimeDATETIME 数据类型,同样适用上述用法:

from sqlalchemy import DateTime

mytable = Table(
    "mytable",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("data", String(50)),
    Column(
        "last_updated",
        DateTime,
        server_default=text(
            "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
        ),
    ),
)

尽管 Column.server_onupdate 不会生成上述 DDL, 但仍可用于向 ORM 表明该字段的更新值应被提取。语法如下:

from sqlalchemy.schema import FetchedValue

class MyClass(Base):
    __tablename__ = "mytable"

    id = Column(Integer, primary_key=True)
    data = Column(String(50))
    last_updated = Column(
        TIMESTAMP,
        server_default=text(
            "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
        ),
        server_onupdate=FetchedValue(),
    )

MySQL / MariaDB have historically expanded the DDL for the TIMESTAMP datatype into the phrase “TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP”, which includes non-standard SQL that automatically updates the column with the current timestamp when an UPDATE occurs, eliminating the usual need to use a trigger in such a case where server-side update changes are desired.

MySQL 5.6 introduced a new flag explicit_defaults_for_timestamp which disables the above behavior, and in MySQL 8 this flag defaults to true, meaning in order to get a MySQL “on update timestamp” without changing this flag, the above DDL must be rendered explicitly. Additionally, the same DDL is valid for use of the DATETIME datatype as well.

SQLAlchemy’s MySQL dialect does not yet have an option to generate MySQL’s “ON UPDATE CURRENT_TIMESTAMP” clause, noting that this is not a general purpose “ON UPDATE” as there is no such syntax in standard SQL. SQLAlchemy’s Column.server_onupdate parameter is currently not related to this special MySQL behavior.

To generate this DDL, make use of the Column.server_default parameter and pass a textual clause that also includes the ON UPDATE clause:

from sqlalchemy import Table, MetaData, Column, Integer, String, TIMESTAMP
from sqlalchemy import text

metadata = MetaData()

mytable = Table(
    "mytable",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("data", String(50)),
    Column(
        "last_updated",
        TIMESTAMP,
        server_default=text(
            "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
        ),
    ),
)

The same instructions apply to use of the DateTime and DATETIME datatypes:

from sqlalchemy import DateTime

mytable = Table(
    "mytable",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("data", String(50)),
    Column(
        "last_updated",
        DateTime,
        server_default=text(
            "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
        ),
    ),
)

Even though the Column.server_onupdate feature does not generate this DDL, it still may be desirable to signal to the ORM that this updated value should be fetched. This syntax looks like the following:

from sqlalchemy.schema import FetchedValue


class MyClass(Base):
    __tablename__ = "mytable"

    id = Column(Integer, primary_key=True)
    data = Column(String(50))
    last_updated = Column(
        TIMESTAMP,
        server_default=text(
            "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
        ),
        server_onupdate=FetchedValue(),
    )

TIMESTAMP 列和 NULL

TIMESTAMP Columns and NULL

MySQL 一贯要求指定 TIMESTAMP 类型的列隐式包含默认值 CURRENT_TIMESTAMP, 即使未显式声明,并且该列同时被设为 NOT NULL。这种行为与所有其他数据类型正好相反:

mysql> CREATE TABLE ts_test (
    -> a INTEGER,
    -> b INTEGER NOT NULL,
    -> c TIMESTAMP,
    -> d TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    -> e TIMESTAMP NULL);
Query OK, 0 rows affected (0.03 sec)

mysql> SHOW CREATE TABLE ts_test;
+---------+-----------------------------------------------------
| Table   | Create Table
+---------+-----------------------------------------------------
| ts_test | CREATE TABLE `ts_test` (
`a` int(11) DEFAULT NULL,
`b` int(11) NOT NULL,
`c` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`d` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`e` timestamp NULL DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1

如上所示,INTEGER 列默认值为 NULL,除非显式指定 NOT NULL;而 TIMESTAMP 类型列则隐式生成 CURRENT_TIMESTAMP 默认值,并强制列为 NOT NULL,尽管未指定。

MySQL 在 5.6 中通过引入 explicit_defaults_for_timestamp 配置标志, 可改变上述行为。启用该设置后,TIMESTAMP 列在默认值和可空性方面的行为将与其他数据类型一致。

然而,考虑到大多数 MySQL 数据库未启用该标志,SQLAlchemy 在声明未设置 nullable=False 的 TIMESTAMP 列时会显式发出 “NULL” 修饰符。 而对于启用了 nullable=False 的列,则显式发出 “NOT NULL”,以兼容新版数据库。以下示例说明该行为:

from sqlalchemy import MetaData, Integer, Table, Column, text
from sqlalchemy.dialects.mysql import TIMESTAMP

m = MetaData()
t = Table(
    "ts_test",
    m,
    Column("a", Integer),
    Column("b", Integer, nullable=False),
    Column("c", TIMESTAMP),
    Column("d", TIMESTAMP, nullable=False),
)

from sqlalchemy import create_engine

e = create_engine("mysql+mysqldb://scott:tiger@localhost/test", echo=True)
m.create_all(e)

输出:

CREATE TABLE ts_test (
    a INTEGER,
    b INTEGER NOT NULL,
    c TIMESTAMP NULL,
    d TIMESTAMP NOT NULL
)

MySQL historically enforces that a column which specifies the TIMESTAMP datatype implicitly includes a default value of CURRENT_TIMESTAMP, even though this is not stated, and additionally sets the column as NOT NULL, the opposite behavior vs. that of all other datatypes:

mysql> CREATE TABLE ts_test (
    -> a INTEGER,
    -> b INTEGER NOT NULL,
    -> c TIMESTAMP,
    -> d TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    -> e TIMESTAMP NULL);
Query OK, 0 rows affected (0.03 sec)

mysql> SHOW CREATE TABLE ts_test;
+---------+-----------------------------------------------------
| Table   | Create Table
+---------+-----------------------------------------------------
| ts_test | CREATE TABLE `ts_test` (
  `a` int(11) DEFAULT NULL,
  `b` int(11) NOT NULL,
  `c` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `d` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `e` timestamp NULL DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1

Above, we see that an INTEGER column defaults to NULL, unless it is specified with NOT NULL. But when the column is of type TIMESTAMP, an implicit default of CURRENT_TIMESTAMP is generated which also coerces the column to be a NOT NULL, even though we did not specify it as such.

This behavior of MySQL can be changed on the MySQL side using the explicit_defaults_for_timestamp configuration flag introduced in MySQL 5.6. With this server setting enabled, TIMESTAMP columns behave like any other datatype on the MySQL side with regards to defaults and nullability.

However, to accommodate the vast majority of MySQL databases that do not specify this new flag, SQLAlchemy emits the “NULL” specifier explicitly with any TIMESTAMP column that does not specify nullable=False. In order to accommodate newer databases that specify explicit_defaults_for_timestamp, SQLAlchemy also emits NOT NULL for TIMESTAMP columns that do specify nullable=False. The following example illustrates:

from sqlalchemy import MetaData, Integer, Table, Column, text
from sqlalchemy.dialects.mysql import TIMESTAMP

m = MetaData()
t = Table(
    "ts_test",
    m,
    Column("a", Integer),
    Column("b", Integer, nullable=False),
    Column("c", TIMESTAMP),
    Column("d", TIMESTAMP, nullable=False),
)


from sqlalchemy import create_engine

e = create_engine("mysql+mysqldb://scott:tiger@localhost/test", echo=True)
m.create_all(e)

output:

CREATE TABLE ts_test (
    a INTEGER,
    b INTEGER NOT NULL,
    c TIMESTAMP NULL,
    d TIMESTAMP NOT NULL
)

MySQL SQL 构造

MySQL SQL Constructs

Object Name Description

match

Produce a MATCH (X, Y) AGAINST ('TEXT') clause.

class sqlalchemy.dialects.mysql.match

Produce a MATCH (X, Y) AGAINST ('TEXT') clause.

E.g.:

from sqlalchemy import desc
from sqlalchemy.dialects.mysql import match

match_expr = match(
    users_table.c.firstname,
    users_table.c.lastname,
    against="Firstname Lastname",
)

stmt = (
    select(users_table)
    .where(match_expr.in_boolean_mode())
    .order_by(desc(match_expr))
)

Would produce SQL resembling:

SELECT id, firstname, lastname
FROM user
WHERE MATCH(firstname, lastname) AGAINST (:param_1 IN BOOLEAN MODE)
ORDER BY MATCH(firstname, lastname) AGAINST (:param_2) DESC

The match() function is a standalone version of the ColumnElement.match() method available on all SQL expressions, as when ColumnElement.match() is used, but allows to pass multiple columns

参数:
  • cols – column expressions to match against

  • against – expression to be compared towards

  • in_boolean_mode – boolean, set “boolean mode” to true

  • in_natural_language_mode – boolean , set “natural language” to true

  • with_query_expansion – boolean, set “query expansion” to true

在 1.4.19 版本加入.

Class signature

class sqlalchemy.dialects.mysql.match (sqlalchemy.sql.expression.Generative, sqlalchemy.sql.expression.BinaryExpression)

method sqlalchemy.dialects.mysql.match.in_boolean_mode() Self

Apply the “IN BOOLEAN MODE” modifier to the MATCH expression.

返回:

a new match instance with modifications applied.

method sqlalchemy.dialects.mysql.match.in_natural_language_mode() Self

Apply the “IN NATURAL LANGUAGE MODE” modifier to the MATCH expression.

返回:

a new match instance with modifications applied.

attribute sqlalchemy.dialects.mysql.match.inherit_cache: bool | None = True

Indicate if this HasCacheKey instance should make use of the cache key generation scheme used by its immediate superclass.

The attribute defaults to None, which indicates that a construct has not yet taken into account whether or not its appropriate for it to participate in caching; this is functionally equivalent to setting the value to False, except that a warning is also emitted.

This flag can be set to True on a particular class, if the SQL that corresponds to the object does not change based on attributes which are local to this class, and not its superclass.

参见

为自定义构造启用缓存支持 - General guideslines for setting the HasCacheKey.inherit_cache attribute for third-party or user defined SQL constructs.

method sqlalchemy.dialects.mysql.match.with_query_expansion() Self

Apply the “WITH QUERY EXPANSION” modifier to the MATCH expression.

返回:

a new match instance with modifications applied.

MySQL 数据类型

MySQL Data Types

与所有SQLAlchemy方言一样,所有已知对MySQL有效的UPPERCASE类型都可以从顶级方言中导入:

from sqlalchemy.dialects.mysql import (
    BIGINT,
    BINARY,
    BIT,
    BLOB,
    BOOLEAN,
    CHAR,
    DATE,
    DATETIME,
    DECIMAL,
    DECIMAL,
    DOUBLE,
    ENUM,
    FLOAT,
    INTEGER,
    LONGBLOB,
    LONGTEXT,
    MEDIUMBLOB,
    MEDIUMINT,
    MEDIUMTEXT,
    NCHAR,
    NUMERIC,
    NVARCHAR,
    REAL,
    SET,
    SMALLINT,
    TEXT,
    TIME,
    TIMESTAMP,
    TINYBLOB,
    TINYINT,
    TINYTEXT,
    VARBINARY,
    VARCHAR,
    YEAR,
)

除了上述类型,MariaDB还支持以下类型:

from sqlalchemy.dialects.mysql import (
    INET4,
    INET6,
)

特定于MySQL或MariaDB,或具有特定构造参数的类型如下:

As with all SQLAlchemy dialects, all UPPERCASE types that are known to be valid with MySQL are importable from the top level dialect:

from sqlalchemy.dialects.mysql import (
    BIGINT,
    BINARY,
    BIT,
    BLOB,
    BOOLEAN,
    CHAR,
    DATE,
    DATETIME,
    DECIMAL,
    DECIMAL,
    DOUBLE,
    ENUM,
    FLOAT,
    INTEGER,
    LONGBLOB,
    LONGTEXT,
    MEDIUMBLOB,
    MEDIUMINT,
    MEDIUMTEXT,
    NCHAR,
    NUMERIC,
    NVARCHAR,
    REAL,
    SET,
    SMALLINT,
    TEXT,
    TIME,
    TIMESTAMP,
    TINYBLOB,
    TINYINT,
    TINYTEXT,
    VARBINARY,
    VARCHAR,
    YEAR,
)

In addition to the above types, MariaDB also supports the following:

from sqlalchemy.dialects.mysql import (
    INET4,
    INET6,
)

Types which are specific to MySQL or MariaDB, or have specific construction arguments, are as follows:

in the dialect module, just imported from sqltypes. this avoids warnings in the sphinx build

Object Name Description

BIGINT

MySQL BIGINTEGER type.

BIT

MySQL BIT type.

CHAR

MySQL CHAR type, for fixed-length character data.

DATETIME

MySQL DATETIME type.

DECIMAL

MySQL DECIMAL type.

ENUM

MySQL ENUM type.

FLOAT

MySQL FLOAT type.

INET4

INET4 column type for MariaDB

INET6

INET6 column type for MariaDB

INTEGER

MySQL INTEGER type.

JSON

MySQL JSON type.

LONGBLOB

MySQL LONGBLOB type, for binary data up to 2^32 bytes.

LONGTEXT

MySQL LONGTEXT type, for character storage encoded up to 2^32 bytes.

MEDIUMBLOB

MySQL MEDIUMBLOB type, for binary data up to 2^24 bytes.

MEDIUMINT

MySQL MEDIUMINTEGER type.

MEDIUMTEXT

MySQL MEDIUMTEXT type, for character storage encoded up to 2^24 bytes.

NCHAR

MySQL NCHAR type.

NUMERIC

MySQL NUMERIC type.

NVARCHAR

MySQL NVARCHAR type.

REAL

MySQL REAL type.

SET

MySQL SET type.

SMALLINT

MySQL SMALLINTEGER type.

TIME

MySQL TIME type.

TIMESTAMP

MySQL TIMESTAMP type.

TINYBLOB

MySQL TINYBLOB type, for binary data up to 2^8 bytes.

TINYINT

MySQL TINYINT type.

TINYTEXT

MySQL TINYTEXT type, for character storage encoded up to 2^8 bytes.

VARCHAR

MySQL VARCHAR type, for variable-length character data.

YEAR

MySQL YEAR type, for single byte storage of years 1901-2155.

class sqlalchemy.dialects.mysql.BIGINT

MySQL BIGINTEGER type.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.BIGINT (sqlalchemy.dialects.mysql.types._IntegerType, sqlalchemy.types.BIGINT)

method sqlalchemy.dialects.mysql.BIGINT.__init__(display_width=None, **kw)

Construct a BIGINTEGER.

参数:
  • display_width – Optional, maximum display width for this number.

  • unsigned – a boolean, optional.

  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.

class sqlalchemy.dialects.mysql.BINARY

The SQL BINARY type.

Class signature

class sqlalchemy.dialects.mysql.BINARY (sqlalchemy.types._Binary)

class sqlalchemy.dialects.mysql.BIT

MySQL BIT type.

This type is for MySQL 5.0.3 or greater for MyISAM, and 5.0.5 or greater for MyISAM, MEMORY, InnoDB and BDB. For older versions, use a MSTinyInteger() type.

Members

__init__()

method sqlalchemy.dialects.mysql.BIT.__init__(length=None)

Construct a BIT.

参数:

length – Optional, number of bits.

class sqlalchemy.dialects.mysql.BLOB

The SQL BLOB type.

Class signature

class sqlalchemy.dialects.mysql.BLOB (sqlalchemy.types.LargeBinary)

method sqlalchemy.dialects.mysql.BLOB.__init__(length: int | None = None)

inherited from the sqlalchemy.types.LargeBinary.__init__ method of LargeBinary

Construct a LargeBinary type.

参数:

length – optional, a length for the column for use in DDL statements, for those binary types that accept a length, such as the MySQL BLOB type.

class sqlalchemy.dialects.mysql.BOOLEAN

The SQL BOOLEAN type.

Class signature

class sqlalchemy.dialects.mysql.BOOLEAN (sqlalchemy.types.Boolean)

method sqlalchemy.dialects.mysql.BOOLEAN.__init__(create_constraint: bool = False, name: str | None = None, _create_events: bool = True, _adapted_from: SchemaType | None = None)

inherited from the sqlalchemy.types.Boolean.__init__ method of Boolean

Construct a Boolean.

参数:
  • create_constraint

    defaults to False. If the boolean is generated as an int/smallint, also create a CHECK constraint on the table that ensures 1 or 0 as a value.

    备注

    it is strongly recommended that the CHECK constraint have an explicit name in order to support schema-management concerns. This can be established either by setting the Boolean.name parameter or by setting up an appropriate naming convention; see 配置约束命名约定 for background.

    在 1.4 版本发生变更: - this flag now defaults to False, meaning no CHECK constraint is generated for a non-native enumerated type.

  • name – if a CHECK constraint is generated, specify the name of the constraint.

class sqlalchemy.dialects.mysql.CHAR

MySQL CHAR type, for fixed-length character data.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.CHAR (sqlalchemy.dialects.mysql.types._StringType, sqlalchemy.types.CHAR)

method sqlalchemy.dialects.mysql.CHAR.__init__(length=None, **kwargs)

Construct a CHAR.

参数:
  • length – Maximum data length, in characters.

  • binary – Optional, use the default binary collation for the national character set. This does not affect the type of data stored, use a BINARY type for binary data.

  • collation – Optional, request a particular collation. Must be compatible with the national character set.

class sqlalchemy.dialects.mysql.DATE

The SQL DATE type.

Class signature

class sqlalchemy.dialects.mysql.DATE (sqlalchemy.types.Date)

class sqlalchemy.dialects.mysql.DATETIME

MySQL DATETIME type.

Members

__init__()

method sqlalchemy.dialects.mysql.DATETIME.__init__(timezone=False, fsp=None)

Construct a MySQL DATETIME type.

参数:
  • timezone – not used by the MySQL dialect.

  • fsp

    fractional seconds precision value. MySQL 5.6.4 supports storage of fractional seconds; this parameter will be used when emitting DDL for the DATETIME type.

    备注

    DBAPI driver support for fractional seconds may be limited; current support includes MySQL Connector/Python.

class sqlalchemy.dialects.mysql.DECIMAL

MySQL DECIMAL type.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.DECIMAL (sqlalchemy.dialects.mysql.types._NumericType, sqlalchemy.types.DECIMAL)

method sqlalchemy.dialects.mysql.DECIMAL.__init__(precision=None, scale=None, asdecimal=True, **kw)

Construct a DECIMAL.

参数:
  • precision – Total digits in this number. If scale and precision are both None, values are stored to limits allowed by the server.

  • scale – The number of digits after the decimal point.

  • unsigned – a boolean, optional.

  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.

class sqlalchemy.dialects.mysql.DOUBLE

MySQL DOUBLE type.

Class signature

class sqlalchemy.dialects.mysql.DOUBLE (sqlalchemy.dialects.mysql.types._FloatType, sqlalchemy.types.DOUBLE)

method sqlalchemy.dialects.mysql.DOUBLE.__init__(precision=None, scale=None, asdecimal=True, **kw)

Construct a DOUBLE.

备注

The DOUBLE type by default converts from float to Decimal, using a truncation that defaults to 10 digits. Specify either scale=n or decimal_return_scale=n in order to change this scale, or asdecimal=False to return values directly as Python floating points.

参数:
  • precision – Total digits in this number. If scale and precision are both None, values are stored to limits allowed by the server.

  • scale – The number of digits after the decimal point.

  • unsigned – a boolean, optional.

  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.

class sqlalchemy.dialects.mysql.ENUM

MySQL ENUM type.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.ENUM (sqlalchemy.types.NativeForEmulated, sqlalchemy.types.Enum, sqlalchemy.dialects.mysql.types._StringType)

method sqlalchemy.dialects.mysql.ENUM.__init__(*enums, **kw)

Construct an ENUM.

E.g.:

Column("myenum", ENUM("foo", "bar", "baz"))
参数:
  • enums – The range of valid values for this ENUM. Values in enums are not quoted, they will be escaped and surrounded by single quotes when generating the schema. This object may also be a PEP-435-compliant enumerated type.

  • strict

    This flag has no effect.

    在 The 版本发生变更: MySQL ENUM type as well as the base Enum type now validates all Python data values.

  • charset – Optional, a column-level character set for this string value. Takes precedence to ‘ascii’ or ‘unicode’ short-hand.

  • collation – Optional, a column-level collation for this string value. Takes precedence to ‘binary’ short-hand.

  • ascii – Defaults to False: short-hand for the latin1 character set, generates ASCII in schema.

  • unicode – Defaults to False: short-hand for the ucs2 character set, generates UNICODE in schema.

  • binary – Defaults to False: short-hand, pick the binary collation type that matches the column’s character set. Generates BINARY in schema. This does not affect the type of data stored, only the collation of character data.

class sqlalchemy.dialects.mysql.FLOAT

MySQL FLOAT type.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.FLOAT (sqlalchemy.dialects.mysql.types._FloatType, sqlalchemy.types.FLOAT)

method sqlalchemy.dialects.mysql.FLOAT.__init__(precision=None, scale=None, asdecimal=False, **kw)

Construct a FLOAT.

参数:
  • precision – Total digits in this number. If scale and precision are both None, values are stored to limits allowed by the server.

  • scale – The number of digits after the decimal point.

  • unsigned – a boolean, optional.

  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.

class sqlalchemy.dialects.mysql.INET4

INET4 column type for MariaDB

在 2.0.37 版本加入.

class sqlalchemy.dialects.mysql.INET6

INET6 column type for MariaDB

在 2.0.37 版本加入.

class sqlalchemy.dialects.mysql.INTEGER

MySQL INTEGER type.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.INTEGER (sqlalchemy.dialects.mysql.types._IntegerType, sqlalchemy.types.INTEGER)

method sqlalchemy.dialects.mysql.INTEGER.__init__(display_width=None, **kw)

Construct an INTEGER.

参数:
  • display_width – Optional, maximum display width for this number.

  • unsigned – a boolean, optional.

  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.

class sqlalchemy.dialects.mysql.JSON

MySQL JSON type.

MySQL supports JSON as of version 5.7. MariaDB supports JSON (as an alias for LONGTEXT) as of version 10.2.

JSON is used automatically whenever the base JSON datatype is used against a MySQL or MariaDB backend.

参见

JSON - main documentation for the generic cross-platform JSON datatype.

The JSON type supports persistence of JSON values as well as the core index operations provided by JSON datatype, by adapting the operations to render the JSON_EXTRACT function at the database level.

class sqlalchemy.dialects.mysql.LONGBLOB

MySQL LONGBLOB type, for binary data up to 2^32 bytes.

Class signature

class sqlalchemy.dialects.mysql.LONGBLOB (sqlalchemy.types._Binary)

class sqlalchemy.dialects.mysql.LONGTEXT

MySQL LONGTEXT type, for character storage encoded up to 2^32 bytes.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.LONGTEXT (sqlalchemy.dialects.mysql.types._StringType)

method sqlalchemy.dialects.mysql.LONGTEXT.__init__(**kwargs)

Construct a LONGTEXT.

参数:
  • charset – Optional, a column-level character set for this string value. Takes precedence to ‘ascii’ or ‘unicode’ short-hand.

  • collation – Optional, a column-level collation for this string value. Takes precedence to ‘binary’ short-hand.

  • ascii – Defaults to False: short-hand for the latin1 character set, generates ASCII in schema.

  • unicode – Defaults to False: short-hand for the ucs2 character set, generates UNICODE in schema.

  • national – Optional. If true, use the server’s configured national character set.

  • binary – Defaults to False: short-hand, pick the binary collation type that matches the column’s character set. Generates BINARY in schema. This does not affect the type of data stored, only the collation of character data.

class sqlalchemy.dialects.mysql.MEDIUMBLOB

MySQL MEDIUMBLOB type, for binary data up to 2^24 bytes.

Class signature

class sqlalchemy.dialects.mysql.MEDIUMBLOB (sqlalchemy.types._Binary)

class sqlalchemy.dialects.mysql.MEDIUMINT

MySQL MEDIUMINTEGER type.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.MEDIUMINT (sqlalchemy.dialects.mysql.types._IntegerType)

method sqlalchemy.dialects.mysql.MEDIUMINT.__init__(display_width=None, **kw)

Construct a MEDIUMINTEGER

参数:
  • display_width – Optional, maximum display width for this number.

  • unsigned – a boolean, optional.

  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.

class sqlalchemy.dialects.mysql.MEDIUMTEXT

MySQL MEDIUMTEXT type, for character storage encoded up to 2^24 bytes.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.MEDIUMTEXT (sqlalchemy.dialects.mysql.types._StringType)

method sqlalchemy.dialects.mysql.MEDIUMTEXT.__init__(**kwargs)

Construct a MEDIUMTEXT.

参数:
  • charset – Optional, a column-level character set for this string value. Takes precedence to ‘ascii’ or ‘unicode’ short-hand.

  • collation – Optional, a column-level collation for this string value. Takes precedence to ‘binary’ short-hand.

  • ascii – Defaults to False: short-hand for the latin1 character set, generates ASCII in schema.

  • unicode – Defaults to False: short-hand for the ucs2 character set, generates UNICODE in schema.

  • national – Optional. If true, use the server’s configured national character set.

  • binary – Defaults to False: short-hand, pick the binary collation type that matches the column’s character set. Generates BINARY in schema. This does not affect the type of data stored, only the collation of character data.

class sqlalchemy.dialects.mysql.NCHAR

MySQL NCHAR type.

For fixed-length character data in the server’s configured national character set.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.NCHAR (sqlalchemy.dialects.mysql.types._StringType, sqlalchemy.types.NCHAR)

method sqlalchemy.dialects.mysql.NCHAR.__init__(length=None, **kwargs)

Construct an NCHAR.

参数:
  • length – Maximum data length, in characters.

  • binary – Optional, use the default binary collation for the national character set. This does not affect the type of data stored, use a BINARY type for binary data.

  • collation – Optional, request a particular collation. Must be compatible with the national character set.

class sqlalchemy.dialects.mysql.NUMERIC

MySQL NUMERIC type.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.NUMERIC (sqlalchemy.dialects.mysql.types._NumericType, sqlalchemy.types.NUMERIC)

method sqlalchemy.dialects.mysql.NUMERIC.__init__(precision=None, scale=None, asdecimal=True, **kw)

Construct a NUMERIC.

参数:
  • precision – Total digits in this number. If scale and precision are both None, values are stored to limits allowed by the server.

  • scale – The number of digits after the decimal point.

  • unsigned – a boolean, optional.

  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.

class sqlalchemy.dialects.mysql.NVARCHAR

MySQL NVARCHAR type.

For variable-length character data in the server’s configured national character set.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.NVARCHAR (sqlalchemy.dialects.mysql.types._StringType, sqlalchemy.types.NVARCHAR)

method sqlalchemy.dialects.mysql.NVARCHAR.__init__(length=None, **kwargs)

Construct an NVARCHAR.

参数:
  • length – Maximum data length, in characters.

  • binary – Optional, use the default binary collation for the national character set. This does not affect the type of data stored, use a BINARY type for binary data.

  • collation – Optional, request a particular collation. Must be compatible with the national character set.

class sqlalchemy.dialects.mysql.REAL

MySQL REAL type.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.REAL (sqlalchemy.dialects.mysql.types._FloatType, sqlalchemy.types.REAL)

method sqlalchemy.dialects.mysql.REAL.__init__(precision=None, scale=None, asdecimal=True, **kw)

Construct a REAL.

备注

The REAL type by default converts from float to Decimal, using a truncation that defaults to 10 digits. Specify either scale=n or decimal_return_scale=n in order to change this scale, or asdecimal=False to return values directly as Python floating points.

参数:
  • precision – Total digits in this number. If scale and precision are both None, values are stored to limits allowed by the server.

  • scale – The number of digits after the decimal point.

  • unsigned – a boolean, optional.

  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.

class sqlalchemy.dialects.mysql.SET

MySQL SET type.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.SET (sqlalchemy.dialects.mysql.types._StringType)

method sqlalchemy.dialects.mysql.SET.__init__(*values, **kw)

Construct a SET.

E.g.:

Column("myset", SET("foo", "bar", "baz"))

The list of potential values is required in the case that this set will be used to generate DDL for a table, or if the SET.retrieve_as_bitwise flag is set to True.

参数:
  • values – The range of valid values for this SET. The values are not quoted, they will be escaped and surrounded by single quotes when generating the schema.

  • convert_unicode – Same flag as that of String.convert_unicode.

  • collation – same as that of String.collation

  • charset – same as that of VARCHAR.charset.

  • ascii – same as that of VARCHAR.ascii.

  • unicode – same as that of VARCHAR.unicode.

  • binary – same as that of VARCHAR.binary.

  • retrieve_as_bitwise

    if True, the data for the set type will be persisted and selected using an integer value, where a set is coerced into a bitwise mask for persistence. MySQL allows this mode which has the advantage of being able to store values unambiguously, such as the blank string ''. The datatype will appear as the expression col + 0 in a SELECT statement, so that the value is coerced into an integer value in result sets. This flag is required if one wishes to persist a set that can store the blank string '' as a value.

    警告

    When using SET.retrieve_as_bitwise, it is essential that the list of set values is expressed in the exact same order as exists on the MySQL database.

class sqlalchemy.dialects.mysql.SMALLINT

MySQL SMALLINTEGER type.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.SMALLINT (sqlalchemy.dialects.mysql.types._IntegerType, sqlalchemy.types.SMALLINT)

method sqlalchemy.dialects.mysql.SMALLINT.__init__(display_width=None, **kw)

Construct a SMALLINTEGER.

参数:
  • display_width – Optional, maximum display width for this number.

  • unsigned – a boolean, optional.

  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.

class sqlalchemy.dialects.mysql.TEXT

MySQL TEXT type, for character storage encoded up to 2^16 bytes.

Class signature

class sqlalchemy.dialects.mysql.TEXT (sqlalchemy.dialects.mysql.types._StringType, sqlalchemy.types.TEXT)

method sqlalchemy.dialects.mysql.TEXT.__init__(length=None, **kw)

Construct a TEXT.

参数:
  • length – Optional, if provided the server may optimize storage by substituting the smallest TEXT type sufficient to store length bytes of characters.

  • charset – Optional, a column-level character set for this string value. Takes precedence to ‘ascii’ or ‘unicode’ short-hand.

  • collation – Optional, a column-level collation for this string value. Takes precedence to ‘binary’ short-hand.

  • ascii – Defaults to False: short-hand for the latin1 character set, generates ASCII in schema.

  • unicode – Defaults to False: short-hand for the ucs2 character set, generates UNICODE in schema.

  • national – Optional. If true, use the server’s configured national character set.

  • binary – Defaults to False: short-hand, pick the binary collation type that matches the column’s character set. Generates BINARY in schema. This does not affect the type of data stored, only the collation of character data.

class sqlalchemy.dialects.mysql.TIME

MySQL TIME type.

Members

__init__()

method sqlalchemy.dialects.mysql.TIME.__init__(timezone=False, fsp=None)

Construct a MySQL TIME type.

参数:
  • timezone – not used by the MySQL dialect.

  • fsp

    fractional seconds precision value. MySQL 5.6 supports storage of fractional seconds; this parameter will be used when emitting DDL for the TIME type.

    备注

    DBAPI driver support for fractional seconds may be limited; current support includes MySQL Connector/Python.

class sqlalchemy.dialects.mysql.TIMESTAMP

MySQL TIMESTAMP type.

Members

__init__()

method sqlalchemy.dialects.mysql.TIMESTAMP.__init__(timezone=False, fsp=None)

Construct a MySQL TIMESTAMP type.

参数:
  • timezone – not used by the MySQL dialect.

  • fsp

    fractional seconds precision value. MySQL 5.6.4 supports storage of fractional seconds; this parameter will be used when emitting DDL for the TIMESTAMP type.

    备注

    DBAPI driver support for fractional seconds may be limited; current support includes MySQL Connector/Python.

class sqlalchemy.dialects.mysql.TINYBLOB

MySQL TINYBLOB type, for binary data up to 2^8 bytes.

Class signature

class sqlalchemy.dialects.mysql.TINYBLOB (sqlalchemy.types._Binary)

class sqlalchemy.dialects.mysql.TINYINT

MySQL TINYINT type.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.TINYINT (sqlalchemy.dialects.mysql.types._IntegerType)

method sqlalchemy.dialects.mysql.TINYINT.__init__(display_width=None, **kw)

Construct a TINYINT.

参数:
  • display_width – Optional, maximum display width for this number.

  • unsigned – a boolean, optional.

  • zerofill – Optional. If true, values will be stored as strings left-padded with zeros. Note that this does not effect the values returned by the underlying database API, which continue to be numeric.

class sqlalchemy.dialects.mysql.TINYTEXT

MySQL TINYTEXT type, for character storage encoded up to 2^8 bytes.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.TINYTEXT (sqlalchemy.dialects.mysql.types._StringType)

method sqlalchemy.dialects.mysql.TINYTEXT.__init__(**kwargs)

Construct a TINYTEXT.

参数:
  • charset – Optional, a column-level character set for this string value. Takes precedence to ‘ascii’ or ‘unicode’ short-hand.

  • collation – Optional, a column-level collation for this string value. Takes precedence to ‘binary’ short-hand.

  • ascii – Defaults to False: short-hand for the latin1 character set, generates ASCII in schema.

  • unicode – Defaults to False: short-hand for the ucs2 character set, generates UNICODE in schema.

  • national – Optional. If true, use the server’s configured national character set.

  • binary – Defaults to False: short-hand, pick the binary collation type that matches the column’s character set. Generates BINARY in schema. This does not affect the type of data stored, only the collation of character data.

class sqlalchemy.dialects.mysql.VARBINARY

The SQL VARBINARY type.

Class signature

class sqlalchemy.dialects.mysql.VARBINARY (sqlalchemy.types._Binary)

class sqlalchemy.dialects.mysql.VARCHAR

MySQL VARCHAR type, for variable-length character data.

Members

__init__()

Class signature

class sqlalchemy.dialects.mysql.VARCHAR (sqlalchemy.dialects.mysql.types._StringType, sqlalchemy.types.VARCHAR)

method sqlalchemy.dialects.mysql.VARCHAR.__init__(length=None, **kwargs)

Construct a VARCHAR.

参数:
  • charset – Optional, a column-level character set for this string value. Takes precedence to ‘ascii’ or ‘unicode’ short-hand.

  • collation – Optional, a column-level collation for this string value. Takes precedence to ‘binary’ short-hand.

  • ascii – Defaults to False: short-hand for the latin1 character set, generates ASCII in schema.

  • unicode – Defaults to False: short-hand for the ucs2 character set, generates UNICODE in schema.

  • national – Optional. If true, use the server’s configured national character set.

  • binary – Defaults to False: short-hand, pick the binary collation type that matches the column’s character set. Generates BINARY in schema. This does not affect the type of data stored, only the collation of character data.

class sqlalchemy.dialects.mysql.YEAR

MySQL YEAR type, for single byte storage of years 1901-2155.

MySQL DML 构造

MySQL DML Constructs

Object Name Description

insert(table)

Construct a MySQL/MariaDB-specific variant Insert construct.

Insert

MySQL-specific implementation of INSERT.

limit(limit)

apply a LIMIT to an UPDATE or DELETE statement

function sqlalchemy.dialects.mysql.insert(table: _DMLTableArgument) Insert

Construct a MySQL/MariaDB-specific variant Insert construct.

The sqlalchemy.dialects.mysql.insert() function creates a sqlalchemy.dialects.mysql.Insert. This class is based on the dialect-agnostic Insert construct which may be constructed using the insert() function in SQLAlchemy Core.

The Insert construct includes additional methods Insert.on_duplicate_key_update().

class sqlalchemy.dialects.mysql.Insert

MySQL-specific implementation of INSERT.

Adds methods for MySQL-specific syntaxes such as ON DUPLICATE KEY UPDATE.

The Insert object is created using the sqlalchemy.dialects.mysql.insert() function.

attribute sqlalchemy.dialects.mysql.Insert.inherit_cache: bool | None = True

Indicate if this HasCacheKey instance should make use of the cache key generation scheme used by its immediate superclass.

The attribute defaults to None, which indicates that a construct has not yet taken into account whether or not its appropriate for it to participate in caching; this is functionally equivalent to setting the value to False, except that a warning is also emitted.

This flag can be set to True on a particular class, if the SQL that corresponds to the object does not change based on attributes which are local to this class, and not its superclass.

参见

为自定义构造启用缓存支持 - General guideslines for setting the HasCacheKey.inherit_cache attribute for third-party or user defined SQL constructs.

attribute sqlalchemy.dialects.mysql.Insert.inserted

Provide the “inserted” namespace for an ON DUPLICATE KEY UPDATE statement

MySQL’s ON DUPLICATE KEY UPDATE clause allows reference to the row that would be inserted, via a special function called VALUES(). This attribute provides all columns in this row to be referenceable such that they will render within a VALUES() function inside the ON DUPLICATE KEY UPDATE clause. The attribute is named .inserted so as not to conflict with the existing Insert.values() method.

小技巧

The Insert.inserted attribute is an instance of ColumnCollection, which provides an interface the same as that of the Table.c collection described at 访问表和列. With this collection, ordinary names are accessible like attributes (e.g. stmt.inserted.some_column), but special names and dictionary method names should be accessed using indexed access, such as stmt.inserted["column name"] or stmt.inserted["values"]. See the docstring for ColumnCollection for further examples.

参见

INSERT…ON DUPLICATE KEY UPDATE(更新插入) - example of how to use Insert.inserted

method sqlalchemy.dialects.mysql.Insert.on_duplicate_key_update(*args: Mapping[Any, Any] | List[Tuple[str, Any]] | ColumnCollection[Any, Any], **kw: Any) Self

Specifies the ON DUPLICATE KEY UPDATE clause.

参数:

**kw – Column keys linked to UPDATE values. The values may be any SQL expression or supported literal Python values.

警告

This dictionary does not take into account Python-specified default UPDATE values or generation functions, e.g. those specified using Column.onupdate. These values will not be exercised for an ON DUPLICATE KEY UPDATE style of UPDATE, unless values are manually specified here.

参数:

*args

As an alternative to passing key/value parameters, a dictionary or list of 2-tuples can be passed as a single positional argument.

Passing a single dictionary is equivalent to the keyword argument form:

insert().on_duplicate_key_update({"name": "some name"})

Passing a list of 2-tuples indicates that the parameter assignments in the UPDATE clause should be ordered as sent, in a manner similar to that described for the Update construct overall in 参数有序更新:

insert().on_duplicate_key_update(
    [
        ("name", "some name"),
        ("value", "some value"),
    ]
)

function sqlalchemy.dialects.mysql.limit(limit: _LimitOffsetType) DMLLimitClause

apply a LIMIT to an UPDATE or DELETE statement

e.g.:

stmt = t.update().values(q="hi").ext(limit(5))

this supersedes the previous approach of using mysql_limit for update/delete statements.

在 2.1 版本加入.

mysqlclient(MySQL-Python 的分支)

mysqlclient (fork of MySQL-Python)

Support for the MySQL / MariaDB database via the mysqlclient (maintained fork of MySQL-Python) driver.

DBAPI

Documentation and download information (if applicable) for mysqlclient (maintained fork of MySQL-Python) is available at: https://pypi.org/project/mysqlclient/

Connecting

Connect String:

mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>

驱动程序状态

Driver Status

mysqlclient DBAPI 是 MySQL-Python DBAPI 的一个维护分支,不再维护。mysqlclient 支持 Python 2 和 Python 3,非常稳定。

The mysqlclient DBAPI is a maintained fork of the MySQL-Python DBAPI that is no longer maintained. mysqlclient supports Python 2 and Python 3 and is very stable.

Unicode

Unicode

请参阅:ref:mysql_unicode 了解有关 unicode 处理的当前建议。

Please see Unicode for current recommendations on unicode handling.

SSL 连接

SSL Connections

mysqlclient 和 PyMySQL DBAPI 接受键“ssl”下的附加字典,可以使用 create_engine.connect_args 字典指定:

engine = create_engine(
    "mysql+mysqldb://scott:tiger@192.168.0.134/test",
    connect_args={
        "ssl": {
            "ca": "/home/gord/client-ssl/ca.pem",
            "cert": "/home/gord/client-ssl/client-cert.pem",
            "key": "/home/gord/client-ssl/client-key.pem",
        }
    },
)

为了方便起见,以下键也可以在 URL 中内联指定,它们将被自动解释到“ssl”字典中:“ssl_ca”、“ssl_cert”、“ssl_key”、“ssl_capath”、“ssl_cipher”、“ssl_check_hostname”。示例如下:

connection_uri = (
    "mysql+mysqldb://scott:tiger@192.168.0.134/test"
    "?ssl_ca=/home/gord/client-ssl/ca.pem"
    "&ssl_cert=/home/gord/client-ssl/client-cert.pem"
    "&ssl_key=/home/gord/client-ssl/client-key.pem"
)

参见

PyMySQL 方言中的 SSL 连接

The mysqlclient and PyMySQL DBAPIs accept an additional dictionary under the key “ssl”, which may be specified using the create_engine.connect_args dictionary:

engine = create_engine(
    "mysql+mysqldb://scott:tiger@192.168.0.134/test",
    connect_args={
        "ssl": {
            "ca": "/home/gord/client-ssl/ca.pem",
            "cert": "/home/gord/client-ssl/client-cert.pem",
            "key": "/home/gord/client-ssl/client-key.pem",
        }
    },
)

For convenience, the following keys may also be specified inline within the URL where they will be interpreted into the “ssl” dictionary automatically: “ssl_ca”, “ssl_cert”, “ssl_key”, “ssl_capath”, “ssl_cipher”, “ssl_check_hostname”. An example is as follows:

connection_uri = (
    "mysql+mysqldb://scott:tiger@192.168.0.134/test"
    "?ssl_ca=/home/gord/client-ssl/ca.pem"
    "&ssl_cert=/home/gord/client-ssl/client-cert.pem"
    "&ssl_key=/home/gord/client-ssl/client-key.pem"
)

参见

SSL 连接 in the PyMySQL dialect

将 MySQLdb 与 Google Cloud SQL 结合使用

Using MySQLdb with Google Cloud SQL

Google Cloud SQL 现推荐使用 MySQLdb 方言。请使用如下 URL 进行连接:

mysql+mysqldb://root@/<dbname>?unix_socket=/cloudsql/<projectid>:<instancename>

Google Cloud SQL now recommends use of the MySQLdb dialect. Connect using a URL like the following:

mysql+mysqldb://root@/<dbname>?unix_socket=/cloudsql/<projectid>:<instancename>

服务器端游标

Server Side Cursors

mysqldb 方言支持服务器端游标。请参阅 服务器端游标

The mysqldb dialect supports server-side cursors. See 服务器端游标.

PyMySQL

Support for the MySQL / MariaDB database via the PyMySQL driver.

DBAPI

Documentation and download information (if applicable) for PyMySQL is available at: https://pymysql.readthedocs.io/

Connecting

Connect String:

mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]

Unicode

Unicode

请参阅 Unicode 了解有关 unicode 处理的当前建议。

Please see Unicode for current recommendations on unicode handling.

SSL 连接

SSL Connections

PyMySQL DBAPI 接受与 MySQLdb 相同的 SSL 参数,详情请参阅 SSL 连接 。更多示例请参阅该部分。

如果服务器使用自动生成的自签名证书或与主机名不匹配(从客户端看到),则可能还需要在 PyMySQL 中指示 ssl_check_hostname = false

connection_uri = (
    "mysql+pymysql://scott:tiger@192.168.0.134/test"
    "?ssl_ca=/home/gord/client-ssl/ca.pem"
    "&ssl_cert=/home/gord/client-ssl/client-cert.pem"
    "&ssl_key=/home/gord/client-ssl/client-key.pem"
    "&ssl_check_hostname=false"
)

The PyMySQL DBAPI accepts the same SSL arguments as that of MySQLdb, described at SSL 连接. See that section for additional examples.

If the server uses an automatically-generated certificate that is self-signed or does not match the host name (as seen from the client), it may also be necessary to indicate ssl_check_hostname=false in PyMySQL:

connection_uri = (
    "mysql+pymysql://scott:tiger@192.168.0.134/test"
    "?ssl_ca=/home/gord/client-ssl/ca.pem"
    "&ssl_cert=/home/gord/client-ssl/client-cert.pem"
    "&ssl_key=/home/gord/client-ssl/client-key.pem"
    "&ssl_check_hostname=false"
)

MySQL-Python 兼容性

MySQL-Python Compatibility

pymysql DBAPI 是 MySQL-python (MySQLdb) 驱动程序的纯 Python 移植,目标是 100% 兼容。MySQL-python 的大部分行为说明也适用于 pymysql 驱动程序。

The pymysql DBAPI is a pure Python port of the MySQL-python (MySQLdb) driver, and targets 100% compatibility. Most behavioral notes for MySQL-python apply to the pymysql driver as well.

MariaDB-Connector

Support for the MySQL / MariaDB database via the MariaDB Connector/Python driver.

DBAPI

Documentation and download information (if applicable) for MariaDB Connector/Python is available at: https://pypi.org/project/mariadb/

Connecting

Connect String:

mariadb+mariadbconnector://<user>:<password>@<host>[:<port>]/<dbname>

驱动状态

Driver Status

MariaDB Connector/Python 允许 Python 程序使用符合 Python DB API 2.0 (PEP-249) 的 API 访问 MariaDB 和 MySQL 数据库。它使用 C 语言编写,并使用 MariaDB Connector/C 客户端库进行客户端/服务器通信。

请注意, mariadb:// 连接 URI 的默认驱动程序仍然是 mysqldb 。使用此驱动程序需要 mariadb+mariadbconnector://

MariaDB Connector/Python enables Python programs to access MariaDB and MySQL databases using an API which is compliant with the Python DB API 2.0 (PEP-249). It is written in C and uses MariaDB Connector/C client library for client server communication.

Note that the default driver for a mariadb:// connection URI continues to be mysqldb. mariadb+mariadbconnector:// is required to use this driver.

MySQL-Connector

Support for the MySQL / MariaDB database via the MySQL Connector/Python driver.

DBAPI

Documentation and download information (if applicable) for MySQL Connector/Python is available at: https://pypi.org/project/mysql-connector-python/

Connecting

Connect String:

mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>

驱动状态

Driver Status

从 SQLAlchemy 2.0.39 开始,MySQL Connector/Python 在驱动程序正常运行的范围内受支持。服务器端游标等功能仍然存在问题,在上游问题修复之前,这些功能仍处于禁用状态。

在 2.0.39 版本发生变更: MySQL Connector/Python 方言已更新,以支持此 DBAPI 的最新版本。此前,MySQL Connector/Python 并未得到完全支持。

MySQL Connector/Python is supported as of SQLAlchemy 2.0.39 to the degree which the driver is functional. There are still ongoing issues with features such as server side cursors which remain disabled until upstream issues are repaired.

在 2.0.39 版本发生变更: The MySQL Connector/Python dialect has been updated to support the latest version of this DBAPI. Previously, MySQL Connector/Python was not fully supported.

使用 MySQL Connector/Python 连接到 MariaDB

Connecting to MariaDB with MySQL Connector/Python

MySQL Connector/Python 连接 MariaDB 时可能会尝试向数据库传递不兼容的排序规则。实验表明,使用 ?charset=utf8mb4&collation=utfmb4_general_ci 或类似的 MariaDB 兼容字符集/排序规则即可实现连接。

MySQL Connector/Python may attempt to pass an incompatible collation to the database when connecting to MariaDB. Experimentation has shown that using ?charset=utf8mb4&collation=utfmb4_general_ci or similar MariaDB-compatible charset/collation will allow connectivity.

asyncmy

Support for the MySQL / MariaDB database via the asyncmy driver.

DBAPI

Documentation and download information (if applicable) for asyncmy is available at: https://github.com/long2ice/asyncmy

Connecting

Connect String:

mysql+asyncmy://user:password@host:port/dbname[?key=value&key=value...]

使用特殊的 asyncio 中介层,asyncmy 方言可用作 SQLAlchemy asyncio 扩展包的后端.

此方言通常仅应与 create_async_engine() 引擎创建函数一起使用:

from sqlalchemy.ext.asyncio import create_async_engine

engine = create_async_engine(
    "mysql+asyncmy://user:pass@hostname/dbname?charset=utf8mb4"
)

Using a special asyncio mediation layer, the asyncmy dialect is usable as the backend for the SQLAlchemy asyncio extension package.

This dialect should normally be used only with the create_async_engine() engine creation function:

from sqlalchemy.ext.asyncio import create_async_engine

engine = create_async_engine(
    "mysql+asyncmy://user:pass@hostname/dbname?charset=utf8mb4"
)

aiomysql

Support for the MySQL / MariaDB database via the aiomysql driver.

DBAPI

Documentation and download information (if applicable) for aiomysql is available at: https://github.com/aio-libs/aiomysql

Connecting

Connect String:

mysql+aiomysql://user:password@host:port/dbname[?key=value&key=value...]

aiomysql 方言是 SQLAlchemy 的第二个 Python asyncio 方言.

使用特殊的 asyncio 中介层,aiomysql 方言可用作 SQLAlchemy asyncio 扩展包的后端.

此方言通常仅应与 create_async_engine() 引擎创建函数一起使用:

from sqlalchemy.ext.asyncio import create_async_engine

engine = create_async_engine(
    "mysql+aiomysql://user:pass@hostname/dbname?charset=utf8mb4"
)

The aiomysql dialect is SQLAlchemy’s second Python asyncio dialect.

Using a special asyncio mediation layer, the aiomysql dialect is usable as the backend for the SQLAlchemy asyncio extension package.

This dialect should normally be used only with the create_async_engine() engine creation function:

from sqlalchemy.ext.asyncio import create_async_engine

engine = create_async_engine(
    "mysql+aiomysql://user:pass@hostname/dbname?charset=utf8mb4"
)

cymysql

Support for the MySQL / MariaDB database via the CyMySQL driver.

DBAPI

Documentation and download information (if applicable) for CyMySQL is available at: https://github.com/nakagami/CyMySQL

Connecting

Connect String:

mysql+cymysql://<username>:<password>@<host>/<dbname>[?<options>]

备注

CyMySQL 方言 尚未作为 SQLAlchemy 持续集成的一部分进行测试,可能存在未解决的问题。推荐的 MySQL 方言是 mysqlclient 和 PyMySQL。

备注

The CyMySQL dialect is not tested as part of SQLAlchemy’s continuous integration and may have unresolved issues. The recommended MySQL dialects are mysqlclient and PyMySQL.

pyodbc

Support for the MySQL / MariaDB database via the PyODBC driver.

DBAPI

Documentation and download information (if applicable) for PyODBC is available at: https://pypi.org/project/pyodbc/

Connecting

Connect String:

mysql+pyodbc://<username>:<password>@<dsnname>

备注

PyODBC for MySQL 方言 尚未作为 SQLAlchemy 持续集成的一部分进行测试 。推荐的 MySQL 方言是 mysqlclient 和 PyMySQL。但是,如果您想使用 mysql+pyodbc 方言,并且需要完全支持 utf8mb4 字符(包括表情符号等补充字符),请务必使用最新版本的 MySQL Connector/ODBC,并在 DSN 或连接字符串中指定驱动程序的“ANSI”( 而非 “Unicode”)版本。

传递精确的 pyodbc 连接字符串:

import urllib

connection_string = (
    "DRIVER=MySQL ODBC 8.0 ANSI Driver;"
    "SERVER=localhost;"
    "PORT=3307;"
    "DATABASE=mydb;"
    "UID=root;"
    "PWD=(whatever);"
    "charset=utf8mb4;"
)
params = urllib.parse.quote_plus(connection_string)
connection_uri = "mysql+pyodbc:///?odbc_connect=%s" % params

备注

The PyODBC for MySQL dialect is not tested as part of SQLAlchemy’s continuous integration. The recommended MySQL dialects are mysqlclient and PyMySQL. However, if you want to use the mysql+pyodbc dialect and require full support for utf8mb4 characters (including supplementary characters like emoji) be sure to use a current release of MySQL Connector/ODBC and specify the “ANSI” (not “Unicode”) version of the driver in your DSN or connection string.

Pass through exact pyodbc connection string:

import urllib

connection_string = (
    "DRIVER=MySQL ODBC 8.0 ANSI Driver;"
    "SERVER=localhost;"
    "PORT=3307;"
    "DATABASE=mydb;"
    "UID=root;"
    "PWD=(whatever);"
    "charset=utf8mb4;"
)
params = urllib.parse.quote_plus(connection_string)
connection_uri = "mysql+pyodbc:///?odbc_connect=%s" % params