我在 Python 2 中使用 MySQLdb,我对在数据库中执行查询有疑问。假设我有一些连接 con
,我用 cur = con.cursor()
实例化了一个游标。以下哪项是将更改提交到数据库的正确方法?如果您能解释正确答案背后的理论,可加分 :)
方法一:
try:
cur.execute('command 1')
con.commit()
cur.execute('command 2')
con.commit()
except MySQLdb.Error as e:
con.rollback()
方法二:
try:
cur.execute('command 1')
cur.execute('command 2')
con.commit()
except MySQLdb.Error as e:
con.rollback()
方法三:
try:
cur.execute('command 1')
try:
cur.execute('command 2')
except MySQLdb.Error as e:
con.rollback()
con.commit()
except MySQLdb.Error as e:
con.rollback()
最佳答案
对于 MySQLdb
,我可能会这样做:
import contextlib
connection = get_connection_somehow()
with contextlib.closing(connection) as con:
with con as cursor:
cursor.execute(query1)
with con as cursor:
cursor.execute(query2)
...
如果要执行的查询不止一两个,当然可以使用循环。
这里有几点需要注意:
- 创建连接的成本有点高。
- 创建游标非常便宜。
MySQLdb.Connection
在用作上下文管理器时会为您提供一个新游标。- 当上下文退出时,如果出现错误则回滚连接,否则将提交更改。
- 参见 https://stackoverflow.com/a/22840557/748858
关于python - MySQLdb - 何时提交和执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38063784/