[英]Postgres: cursor.execute(“COMMIT”) vs. connection.commit()
[英]After execute connection.commit(), why the others cursor.execute() not work correctly?
我使用PyMysql lib向数据库中添加了一些行,我得到了很长的SQL列表,也许超过150000行。 所以我想每隔5000次执行一次commit,代码在这里:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.