SQLite(Python apsw)无法回滚,因为它很忙

2024-04-27 05:33:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Pythonapsw绑定处理SQLite数据库。代码是这样的:

with apsw.Connection(path) as t:
    c = t.cursor()
    c.execute(...)
    ... more code ...
    if c.execute(...).next()[0]:
        raise Exception

我希望with语句放置一个保存点,raise语句将回滚到该保存点(或者,如果没有要引发的内容,则提交事务)。它提交得很好,但是当有东西要raise时,它拒绝回滚:

^{pr2}$

我不知道先去哪儿看看。据我所知,这个错误意味着有另一个连接阻止了访问,但从代码来看,这不是这样的,如果是这样的话,提交时也会失败吗?在

SQLite 3.7.7.1,匹配apsw,Python2.7。在


Tags: path代码数据库executesqlitemoreaswith
2条回答

我发现了:

if c.execute(...).next()[0]:
    raise Exception

问题是,在我用next()得到下一行时,底层游标保持活动状态,准备返回更多行。必须明确关闭:

^{pr2}$

或者隐式地,通过读取所有数据:

if list(c.execute(...))[0][0]:
    raise Exception

更新。为了方便起见,我编写了一个Python类,它包装了apsw.Cursor,并提供了{a1},因此我可以编写:

with Cursor(connection) as c:
    c.execute(...)

这是SQLite本身的一个问题。它在2012年3月的3.7.11版本中被修复。从changelog

Pending statements no longer block ROLLBACK. Instead, the pending statement will return SQLITE_ABORT upon next access after the ROLLBACK.

相关问题 更多 >