python - 为什么 Python 的 DB-API 中的连接没有 "begin"操作?

标签 python sql python-db-api

在 mysql-python 中使用游标我曾经调用“BEGIN;”、“COMMIT;”和“ROLLBACK;”明确如下:

try:
    cursor.execute("BEGIN;")
    # some statements
    cursor.execute("COMMIT;")
except:
    cursor.execute("ROLLBACK;")

然后,我发现底层连接对象有相应的方法:

try:
    cursor.connection.begin()
    # some statements
    cursor.connection.commit()
except:
    cursor.connection.rollback()

检查 DB-API PEP我发现它没有提到连接对象的 begin() 方法,即使是扩展也是如此。

顺便说一下,当你使用这个方法时,Mysql-python 会抛出 DeprecationWarning。例如,sqlite3.connection 根本没有该方法。

问题是为什么PEP中没有这个方法?该语句是否在某种程度上是可选的,调用 commit() 是否足够?

最佳答案

a this previously asked question .通常用于交易的“协议(protocol)”是:

cursor = conn.cursor()
try:
    cursor.execute(...)
except DatabaseError:
    conn.rollback()
    raise
else:
    conn.commit()
finally:
    cursor.close()

从 python 2.6 开始 sqlite Connection objects can be used as context managers that automatically commit or rollback transactions .

关于python - 为什么 Python 的 DB-API 中的连接没有 "begin"操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2546926/

相关文章:

sql - 通过 SQL 根据相同的行组分配组名

python - Django 中的游标是否在打开的事务中运行?

python - 是否有支持 xmltype 列的 Python Oracle 包装器?

SQL如何模拟异或?

sql - 何时使用第五范式(5NF)?

sql-server - 来自 pyodbc 的 sql 打印语句

python - PostgreSQL/performance 一个通用游标或为每个查询创建

python - Pandas GroupBy,将新的数字列表列与另一列数字列表进行比较

python - Conda 命令静默失败

java - Python 和 Java 在 RegEx 语法上的差异