我应该在 while 循环内还是外部提交我的数据库?

Should I commit to my database inside the while loop or outside?

我有这样的东西:

# pseudo code
while True:
   result = make_request_for_data(my_http_request)
   query = "INSERT INTO my_table (col1, col2) VALUES (%s, %s);"

   for data in result:
       cursor.execute(query, data)

   connection.commit() # should this be inside while loop or outside?

   if result is None:  # some breaking mechanism
       break

cursor.close()
connection.close()

是否有性能优势?为什么?我会做一些计时,但想知道为什么一个比另一个好,如果是这样的话。

这取决于,它所依赖的东西比性能重要得多。问问自己:

Is the entire loop a single atomic business operation, or is each iteration of the loop a single atomic business operation?

也就是说,假设您要循环 10 条记录,而记录 #5 以某种方式失败了。 1-4 还应该提交吗?如果是这样,请在循环内提​​交。如果不是,则在循环外提交。

更改提交数据的位置确实会影响性能,但更重要的是它会影响正在实施的系统的逻辑。