我查詢兩個數據庫以獲得兩個關係。我對這些關係進行過一次形成地圖的演練,然後再進行一些計算。但是,當我第二次嘗試迭代相同的關係時,我發現實際上沒有發生迭代。下面是代碼:多次對錶進行迭代Python SQLAlchemy
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循環'實際上並未發生。爲什麼我不能第二次迭代Relation1
和Relation2
?
有沒有辦法重新打開遊標? –
@JeremyFisher - 據我所知,SQL Alchemy/DBAPI不支持[可滾動遊標](https://en.wikipedia.org/wiki/Cursor_%28databases%29#Scrollable_cursors),所以你的光標回來是一次使用而忘記的交易。 – birryree