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