From the documentation of Python Sqlite3
executescript(sql_script)
This is a nonstandard convenience method for executing multiple SQL statements at once. It issues a COMMIT statement first, then executes the SQL script it gets as a parameter. This method disregards isolation_level; any transaction control must be added to sql_script.
My problem: I am executing a series of sql scripts with multiples statements, e.g.:
db = sqlite3.connect(my_db_path)
for sql_file in files:
f = open(sql_file)
update_script = f.read()
f.close()
db.executescript(update_script)
The executescript()
method makes a commit before executing so I can't have a transaction control over all files to rollback to the initial state if it fails in the middle of the process because it commits on each iteration.
I need a way to commit only at the end after the for loop and not at the end of each iteration. I didn't manage to make the method execute()
work because it doesn't support multiple statements and I also did not manage to make it work with executemany()
method because it would fail if my file happens to have only one statement.
Any suggestions?
CodePudding user response:
If all the scripts need to be executed as one transaction, instead of read, execute, read, execute, ..... try read, read, read.....execute. In other words, read the contents of all the files into update_script
, then execute it.