简体   繁体   English

没有 COMMIT 事务的 Python Sqlite3 执行脚本(sql_script)

[英]Python Sqlite3 executescript(sql_script) without COMMIT transaction

From the documentation of Python Sqlite3来自Python Sqlite3文档

executescript(sql_script)

This is a nonstandard convenience method for executing multiple SQL statements at once.这是一次执行多个 SQL 语句的非标准便捷方法。 It issues a COMMIT statement first, then executes the SQL script it gets as a parameter.它首先发出 COMMIT 语句,然后执行它作为参数获取的 SQL 脚本。 This method disregards isolation_level;该方法无视isolation_level; any transaction control must be added to sql_script.任何事务控制都必须添加到 sql_script。

My problem: I am executing a series of sql scripts with multiples statements, eg:我的问题:我正在执行一系列带有多个语句的 sql 脚本,例如:

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. executescript()方法在执行之前进行提交,因此如果它在过程中间失败,我无法对所有文件进行事务控制以回滚到初始状态,因为它在每次迭代中提交。

I need a way to commit only at the end after the for loop and not at the end of each iteration.我需要一种仅在 for 循环之后而不是在每次迭代结束时提交的方法。 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.我没有设法使方法execute()工作,因为它不支持多个语句,而且我也没有设法使它与executemany()方法一起工作,因为如果我的文件碰巧只有一个语句,它就会失败。

Any suggestions?有什么建议?

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.换句话说,将所有文件的内容读入update_script ,然后执行它。

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

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