Python DB-Api 何时提交多个 inserts/updates
Python DB-Api when to commit on multiple inserts/updates
我有一个函数可以更新数据库中的一行。
def update_one_row(conn, condition, value):
with conn.cursor() as curr:
curr.execute("""UPDATE persons p
SET p.age=%s
WHERE p.name=%s;""",
(value, condition))
是否可以多次(几千)次使用此函数,然后再执行 conn.commit()
,如下所示:
from pymysql import Connect
connect_args = {...}
conn = Connect(**connect_args)
for condition, value in iterable_of_conditions_values:
update_one_row(conn, condition, value)
# Here I visually inspect in jupyter notebook if things went as expected and I accidentaly did not screw up
conn.commit()
或者我应该将 curr
而不是 conn
传递给 update_one_row
?
我知道 curr.executemany()
,但我更喜欢显式循环。有性能差异吗?
总的来说,我对游标的使用和何时提交感到很迷茫。
当您想要应用一系列更改并希望在某处遇到问题时能够回滚/不提交时,您必须提交。在最常见的情况下,当更改仅在一起应用时才有意义时使用它。
在你的情况下,在几千之后提交是有意义的。为了不让你的系统过于复杂,最好的方法是在你的循环之后只提交一次。否则,您将不得不跟踪更新或未更新的行。
我有一个函数可以更新数据库中的一行。
def update_one_row(conn, condition, value):
with conn.cursor() as curr:
curr.execute("""UPDATE persons p
SET p.age=%s
WHERE p.name=%s;""",
(value, condition))
是否可以多次(几千)次使用此函数,然后再执行 conn.commit()
,如下所示:
from pymysql import Connect
connect_args = {...}
conn = Connect(**connect_args)
for condition, value in iterable_of_conditions_values:
update_one_row(conn, condition, value)
# Here I visually inspect in jupyter notebook if things went as expected and I accidentaly did not screw up
conn.commit()
或者我应该将 curr
而不是 conn
传递给 update_one_row
?
我知道 curr.executemany()
,但我更喜欢显式循环。有性能差异吗?
总的来说,我对游标的使用和何时提交感到很迷茫。
当您想要应用一系列更改并希望在某处遇到问题时能够回滚/不提交时,您必须提交。在最常见的情况下,当更改仅在一起应用时才有意义时使用它。
在你的情况下,在几千之后提交是有意义的。为了不让你的系统过于复杂,最好的方法是在你的循环之后只提交一次。否则,您将不得不跟踪更新或未更新的行。