简体   繁体   English

从Windows命令行运行脚本时,由于“ SQL语句正在进行”,Python sqlite3无法回滚事务。

[英]Python sqlite3 cannot rollback transaction due to 'SQL statements in progress' when script run from Windows command line.

I'm operating table merges on some sqlite3 databases in Python. 我正在使用Python在一些sqlite3数据库上进行表合并。 When one of the merging functions spots an error due to a condition, it returns False. 当合并功能之一发现由于条件导致的错误时,它将返回False。 If a False is returned then a rollback is performed. 如果返回False,则执行回滚。 Something like this: 像这样:

con_out = sqlite3.connect('db',isolation_level=None)
out_cursor = con_out.cursor()
try:
   out_cursor.execute("begin")
   if not merge_table(in_cursor, out_cursor, verbose):
      logging.error("rolling back changes")
      out_cursor.execute("rollback")
      return False
except Exception as e:
   logging.error("rolling back changes: %s" % (str(e)))
   out_cursor.execute("rollback")
   return False

Now when this code is executed from PyCharm interpreter, and a False is returned, there is no problem. 现在,当从PyCharm解释器执行此代码并返回False时,就没有问题了。 It rolls back normally as expected. 它会按预期正常回滚。 However, when the script is run from Windows command line, it gives me this error: 但是,从Windows命令行运行脚本时,它给了我这个错误:

sqlite3.OperationalError: cannot rollback transaction - SQL statements in progress

Just in case if anyone wondering, I found the problem. 万一有人怀疑,我发现了问题。 Before I even set the isolation_level of the database to None, I execute: 在将数据库的isolation_level设置为“无”之前,我先执行:

out_cursor.execute("PRAGMA journal_mode = MEMORY")
db_con_out.commit()

For some reason this statement was not committing and was still in progress, blocking other transactions. 由于某种原因,该语句未提交,仍在执行中,从而阻止了其他事务。 When I wrapped it with this code down below, it worked 当我用下面的代码包装它时,它起作用了

db_con_out.isolation_level = None
db_cursor.execute("begin")
if not execute_sql(db_cursor, "PRAGMA journal_mode = MEMORY;"):
    db_cursor.execute("rollback")
    sys.exit()
else:
    db_cursor.execute("commit")

It commit just fine telling from the debugger. 它可以很好地从调试器中得知。 I don't know the actual reason behind this though. 我不知道背后的真正原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM