Sqlite3游标实时更新?

问题描述 投票:2回答:1

有人可以向我解释一下:

import sqlite3

db = sqlite3.connect(':memory:')

db.execute('create table t1 (id integer primary key, val text)')
db.execute('create table t2 (id integer primary key, val text)')

c = db.cursor()
c.execute('insert into t1 values (?, ?)', (1, 'a'))
c.execute('insert into t2 values (?, ?)', (1, 'b'))
c.execute('insert into t1 values (?, ?)', (2, 'c'))
c.execute('insert into t2 values (?, ?)', (2, 'd'))

c.execute('''select t1.id, t1.val, t2.val
             from t1
             left join t2 using (id)
             where t1.id is not null

             union all

             select t2.id, t1.val, t2.val
             from t2
             left join t1 using (id)
             where t2.id is not null
             and t1.id is null

             ''')
for row in c:
    print(row[0])
    if row[0] == 1:
        c2 = db.cursor()
        c2.execute('delete from t1 where id = ?', (row[0],))

如果我注释掉最后三行,则输出为:

1
2

但如果我取消注释最后三行,则输出为:

1
2
1

即。已使用第二个游标中执行的DML结果更新了第一个游标。

这是预期的行为吗?有什么方法可以预防吗?

我正在运行Python 3.6.3(根据Ubuntu 17.10),以防万一。

python sql python-3.x sqlite python-3.6
1个回答
3
投票

如果可能,SQLite会根据需要计算结果行。但这并非总是可行,所以无法保证。

您永远不应该修改当前正在另一个查询中读取的任何表。 (数据库可能以不明显的方式扫描表,因此即使更改其他行也可能会更改枚举。)

如果您打算进行此类修改,则必须在执行更改之前读取所有行,例如for row in c.fetchall()。或者,只需单步读取表格,重新搜索最后一个查询所在的位置,即:

SELECT ... FROM MyTable WHERE ID > :LastID ORDER BY ID LIMIT 1;
© www.soinside.com 2019 - 2024. All rights reserved.