首页 文章

多次迭代表SQL SQLAlchemy

提问于
浏览
0

我查询了两个数据库以获得两个关系 . 我曾经试图用这些关系来形成 Map ,然后再次进行一些计算 . 但是,当我尝试第二次迭代相同的关系时,我发现实际上没有发生迭代 . 这是代码:

dev_connect = dev_engine.connect()
prod_connect = prod_engine.connect() # from a different database
Relation1 = dev_engine.execute(sqlquery1)
Relation2 = prod_engine.execute(sqlquery)

before_map = {}
after_map = {}
for row in Relation1:
    before_map[row['instrument_id']] = row
for row2 in Relation2:
    after_map[row2['instrument_id']] = row2

update_count = insert_count = delete_count = 0

change_list = []
count =0
for prod_row in Relation2:
    count += 1
    result = list(prod_row)
    ...
    change_list.append(result)

count2 = 0
for before_row in Relation1:
    count2 += 1
    result = before_row
    ...

print count, count2 # prints 0

before_mapafter_map 不为空,因此 Relation1Relation2 肯定有元组 . 然而 countcount2 是0,所以 prod_rowbefore_row 'for loops'不是't actually occurring. Why can' t我第二次遍历 Relation1Relation2

1 回答

  • 2

    当您在SQL Alchemy引擎上调用 execute 时,会返回一个ResultProxy,它是 DBAPI 游标的外观,指向查询返回的行 .

    迭代 ResultProxy 的所有结果后,它会自动关闭底层游标,因此只需迭代它就不能再使用结果,如documented on the SQLAlchemy page

    返回的结果是ResultProxy的一个实例,它引用DBAPI游标并提供与DBAPI游标大致兼容的接口 . 当ResultProxy的所有结果行(如果有)耗尽时,DBAPI游标将被关闭 .

    您可以通过以下几种方式解决问题:

    • 将结果存储在 list 中 . 只需对返回的行做一个 list -理解:
    Relation1 = dev_engine.execute(sqlquery1)
    relation1_items = [r for r in Relation1]
    # ...
    # now you can iterate over relation1_items as much as you want
    
    • 在一次通过返回的每个行集中执行您需要的所有操作 . 我不知道您的计算的完整范围是否需要在 before_mapafter_map 对象之间进行交叉引用 .

相关问题