执行完connection.commit()后,为什么其他的cursor.execute()不能正常工作?

After execute connection.commit(), why the others cursor.execute() not work correctly?

我正在使用 PyMysql 库向我的数据库添加一些行,我得到了一个很长的 SQL 列表,可能超过 150000 行。所以我想每5000次执行commit my,代码在这里:

import pymysql

sql_list = ["sql1", "sql2", "sql3", ...]  # Very long list, more than 150000 rows
conn = pymysql.connect(
    host="localhost",
    port=3306,
    user="user",
    password="abc-123",
    database="test",
    charset="utf8"
)
cursor = conn.cursor()

flag = 0  # flag, for the count
for sql in sql_list:
    cursor.execute(sql)
    flag += 1
    if flag > 5000:
        conn.commit()
        flag = 0

当我尝试 运行 这个脚本时,我在我的数据库中得到了一些行,但不是全部。
然后我将代码更改为:

import pymysql

sql_list = ["sql1", "sql2", "sql3", ...]  # Very long list, more than 150000 rows
conn = pymysql.connect(
    host="localhost",
    port=3306,
    user="user",
    password="abc-123",
    database="test",
    charset="utf8"
)
cursor = conn.cursor()

# flag = 0  # flag, for the count
for sql in sql_list:
    cursor.execute(sql)
    # flag += 1
    # if flag > 5000:
    #     conn.commit()
    #     flag = 0
conn.commit()

它工作正常!为什么?我的考虑是多余的吗?
任何建议将不胜感激。

ChowRex,您每 5000 行提交一次。我猜想在最后一次提交之后还有其他要执行的 sql,但这些都没有提交。我认为您需要最后一次提交。

flag = 0  # flag, for the count
for sql in sql_list:
    cursor.execute(sql)
    flag += 1
    if flag > 5000:
        conn.commit()
        flag = 0
conn.commit()