【问题标题】:Sqlite3 cursors live updating?Sqlite3 游标实时更新?
【发布时间】:2018-06-13 08:14:51
【问题描述】:

谁能给我解释一下:

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】:

    如果可能,SQLite 会按需计算结果行。但这并不总是可能的,因此无法保证。

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

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

    SELECT ... FROM MyTable WHERE ID > :LastID ORDER BY ID LIMIT 1;
    

    【讨论】:

    • 嗨,您将我的问题 (stackoverflow.com/questions/49080463/…) 标记为重复并指向此处。谢谢,类似的。根据更改的数据,这里的行为是合理的。就我而言,我不这么认为(重新阅读未被更新更改的行)。 SQLite 可以是多用户数据库并在服务器 AFAIK 中使用,因此应该在读取期间进行更新。大型数据集的 fetchall 不是“好”恕我直言。你怎么看?
    • 要澄清问题中的代码会发生什么,请将评论放在那里。
    • 我有 python3 代码与本地 sqlite3 数据库一起使用,该数据库从表中进行选择,并在“for”循环中更新同一张表中的某些行。我注意到在循环中进行“提交”会增加循环处理的行数,在调试打印中“提交”之后再次出现一些行,并且其他行不是更新的行,正如我在调试打印输出中看到的那样,通过唯一 ID。额外的行数不等于更新的行数。
    猜你喜欢
    • 2015-03-01
    • 2018-05-18
    • 1970-01-01
    • 2018-12-03
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    相关资源
    最近更新 更多