生成器中的Python DBAPI游标提取过早关闭

时间:2018-08-07 22:09:17

标签: python sqlite generator python-db-api

import dbapi2
conn = dbapi2.connect("db", autocommit=True)

def fetch_generator():
    cursor = conn.cursor()
    for res in cursor.execute('select * from table'):
        yield res

def generator_1():
    for x in fetch_generator():
        yield x

def generator_2():
    for x in generator_1():
        yield x

if __name__ == '__main__':
    for x in generator_2():
        print(x)

这会在for x in fetch_generator()

处引发错误

错误:dbapi2.InterfaceError: Attempted to use a closed cursor

为什么光标与生成器链一起关闭?是范围问题,上下文管理器是一种解决方案吗?如何使光标不会自动调用delclose(不确定何时),并保持打开状态。

0 个答案:

没有答案