我想在 mysql 脚本下使用 pymysql 来运行。
START TRANSACTION;
BEGIN;
insert into ~~~
COMMIT;
我的Python源代码是
connection = pymysql.connect(~~~~~~~)
with connection.cursor() as cursor :
connection.begin()
cursor.execute(~~.sql)
connection.commit()
connection.close()
我的问题是“connection.begin()”与“START TRANSACTION; BEGIN;”是一样的?我想使用“开始交易;开始;”
根据 PyMySQL 文档/示例(单数...这似乎不是一个得到很好支持的包),默认情况下自动提交处于关闭状态,因此您确实需要运行
connection.commit()
才能实际完成交易。
他们的例子:
import pymysql.cursors
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('[email protected]', 'very-secret'))
# connection is not autocommit by default. So you must commit to save changes.
connection.commit()
finally:
connection.close()
pymysql.connections.Connection.begin
请参阅手册了解更多信息
PyMySQL 包的文档目前确实非常简单,因此很难说出事务的预期实现是什么。以下是我认为最好的实现方式:
让
credentials
成为带有连接详细信息的字典,例如
credentials = {'host': 'localhost', 'port': 3306, 'user': 'user', 'password':'password'}
然后让
query01
将一些值插入到最初为空的表 table
中,其中字段为 a
和 b
以及 query02
将它们读回给您:
query01 = "INSERT INTO table (a, b) VALUES (1, 2), (3,4);"
query02 = "SELECT * FROM table;"
事务应该执行一些查询,并在发生错误时回滚所有更改,或者在最后提交所有更改。您可以按如下方式实现:
with pymysql.connect(**credentials) as conn:
try:
with conn.cursor() as cursor:
# run queries here
conn.commit()
except:
conn.rollback()
raise
外部上下文管理器将处理关闭连接,因此不需要进一步调用
conn.close()
。同样,内部上下文管理器将关闭光标。
例如,运行两个查询然后引发错误将回滚所有更改:
with pymysql.connect(**credentials) as conn:
try:
with conn.cursor() as cursor:
cursor.execute(query01)
cursor.execute(query02)
print(cursor.fetchall()) # Returns ((13, 14),)
raise ValueError("Some error occured, revert changes.")
conn.commit()
except:
conn.rollback()
虽然
query02
确实返回了table
写入到query01
的值,但回滚后表再次为空。删除抬起 ValueError
的行,然后所有内容都会被提交并且值保留在表中。