gpt4 book ai didi

sqlite - SQLite 中的事务

转载 作者:行者123 更新时间:2023-12-03 16:21:15 25 4
gpt4 key购买 nike

我现在知道在 MySQL有长长list导致隐式提交的语句,如 CREATE , ALTER等等。我想知道SQLite中是否有这样的东西.

换句话说,我想知道是否,例如 CREATE TABLE和其他一些构造会导致自动提交,因此无法回滚?

我自己测试过,在我看来,就像 SQLite表现得像 MySQL ,但我不确定这一点,我想引用列出所有此类命令的文档(我找不到)。

此外,我想知道是否可以调整一些 sqlite 参数以防止它形成自动提交 CREATE和其他声明。

编辑

一个额外的想法。例如,我们都知道,在 SQLite 中重命名字段或更改其类型(使用一个命令)是不可能的,但是为了做到这一点,我们必须创建一个具有所需架构的新表并将数据导入到该表中。显然,这样的操作应该在单个事务中实现,但如果实际上CREATE TABLE 怎么办?和 DROP TABLE命令导致自动提交?

反例

import sqlite3

cnx = sqlite3.connect("test.db")
cursor = cnx.cursor()
cursor.execute("CREATE TABLE funky (attr_1_ integer)")
cnx.rollback()

正如你所看到的,我没有使用任何特殊的编译指示,我什至没有明确提交,但是当我运行它然后转到 sqlite3 提示符时,我看到表 funky仍然存在。

最佳答案

除了一些特殊的 PRAGMAs ( foreign_keys , journal_mode ),所有 SQL 命令都是 fully transactional :

No changes can be made to the database except within a transaction.



仅当您不使用显式事务时,SQLite 才会使用自动提交:

Any command that changes the database (basically, any SQL command other than SELECT) will automatically start a transaction if one is not already in effect. Automatically started transactions are committed when the last query finishes.



为了能够回滚 CREATE TABLE,您必须
  • 使用显式事务,和
  • (仅在 Python 中)禁用 Python 的 autocommit mode :

  • import sqlite3

    cnx = sqlite3.connect("test.db")
    cnx.isolation_level = None
    cursor = cnx.cursor()
    cursor.execute("BEGIN")
    cursor.execute("CREATE TABLE funky (attr_1_ integer)")
    cursor.execute("ROLLBACK")

    关于sqlite - SQLite 中的事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34042752/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com