我使用PyMysql库将一些行添加到我的数据库中,我得到了一个很长的SQL列表,可能超过150000行。因此,我想每5000次执行一次提交,代码如下:
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()它正常工作!为什么?我的考虑是不是多余了?
任何建议都将不胜感激。
发布于 2019-09-12 08:33:57
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()https://stackoverflow.com/questions/57902209
复制相似问题