我查询了两个数据库以获得两个关系 . 我曾经试图用这些关系来形成 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_map
和 after_map
不为空,因此 Relation1
和 Relation2
肯定有元组 . 然而 count
和 count2
是0,所以 prod_row
和 before_row
'for loops'不是't actually occurring. Why can' t我第二次遍历 Relation1
和 Relation2
?
1 回答
当您在SQL Alchemy引擎上调用
execute
时,会返回一个ResultProxy,它是DBAPI
游标的外观,指向查询返回的行 .迭代
ResultProxy
的所有结果后,它会自动关闭底层游标,因此只需迭代它就不能再使用结果,如documented on the SQLAlchemy page:您可以通过以下几种方式解决问题:
list
中 . 只需对返回的行做一个list
-理解:before_map
和after_map
对象之间进行交叉引用 .