You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免Python Sqlite3 executescript自动提交,实现多SQL脚本全局事务控制

核心问题说明

executescript方法触发自动COMMIT的特性,导致跨多次调用无法实现全局事务控制,以下是两种可行解决方案:


方案一:拆分单条SQL语句逐个执行(推荐)

通过第三方库sqlparse拆分SQL文件中的多语句,自行控制全局事务,兼容性最强,适合所有场景。

  • 先安装依赖:pip install sqlparse
  • 实现代码:
import sqlite3
import sqlparse

db = sqlite3.connect(my_db_path)
# 关闭驱动层自动事务管理,完全手动控制
db.isolation_level = None
cursor = db.cursor()

try:
    # 开启全局事务
    cursor.execute("BEGIN TRANSACTION;")
    for sql_file in files:
        with open(sql_file, 'r', encoding='utf-8') as f:
            sql_content = f.read()
        # 拆分有效SQL语句,过滤注释和空内容
        statements = sqlparse.split(
            sqlparse.format(sql_content, strip_comments=True, strip_whitespace=True)
        )
        for stmt in statements:
            stmt = stmt.strip()
            if not stmt:
                continue
            cursor.execute(stmt)
    # 全部执行成功提交
    cursor.execute("COMMIT;")
except Exception as e:
    # 任意异常触发全量回滚
    cursor.execute("ROLLBACK;")
    raise e
finally:
    cursor.close()
    db.close()

方案二:拼接所有脚本单次执行executescript

不需要引入第三方依赖,适合SQL脚本内容可控(无内置COMMIT/ROLLBACK语句)的场景。
executescript仅在调用时触发一次自动COMMIT,将所有脚本拼接后单次调用即可绕过多次COMMIT的问题。

  • 实现代码:
import sqlite3

db = sqlite3.connect(my_db_path)
# 全局脚本开头手动开启事务
full_script = "BEGIN TRANSACTION;\n"

for sql_file in files:
    with open(sql_file, 'r', encoding='utf-8') as f:
        full_script += f.read() + "\n"

# 全局脚本结尾添加提交语句
full_script += "COMMIT;"

try:
    db.executescript(full_script)
except Exception as e:
    # 执行出错主动回滚
    db.execute("ROLLBACK;")
    raise e
finally:
    db.close()

内容的提问来源于stack exchange,提问作者gvn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 08:15:11