简体   繁体   中英

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. When one of the merging functions spots an error due to a condition, it returns False. If a False is returned then a rollback is performed. 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. It rolls back normally as expected. However, when the script is run from Windows command line, it gives me this error:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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