處理成批記錄
目前表現非常棒!正如 Jason 在影片中所說,有時你需要處理很大的 ResultProxy,但記憶體不足以一次載入所有結果。為了因應這種情況,你可以在迴圈中使用 .fetchmany() 從 ResultProxy 取得一批一批的列。使用 .fetchmany() 時,帶入你想要的記錄數作為引數。當回傳為空清單時,代表已沒有可擷取的列,你也就處理完這個查詢的所有結果。接著要使用 .close() 方法關閉與資料庫的連線。
現在你可以實作看看,系統已替你預先載入一個大型的 ResultProxy,名為 results_proxy,供你練習使用。
本練習屬於課程
Python 資料庫入門
練習說明
- 使用
while迴圈檢查是否還有more_results。 - 在迴圈中,對
results_proxy套用.fetchmany()方法,每次取得50筆記錄,並將結果儲存為partial_results。 - 擷取後,如果
partial_results是空清單(也就是等於[]),將more_results設為False。 - 迴圈走訪
partial_results,如果row.state是state_count字典中的鍵,將state_count[row.state]加 1;否則將state_count[row.state]設為 1。 - 在 while 迴圈之後,使用
.close()關閉 ResultProxyresults_proxy。 - 送出答案以印出
state_count。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Start a while loop checking for more results
while more_results:
# Fetch the first 50 results from the ResultProxy: partial_results
partial_results = ____
# if empty list, set more_results to False
if partial_results == []:
more_results = ____
# Loop over the fetched records and increment the count for the state
for row in ____:
if row.state in state_count:
____
else:
____
# Close the ResultProxy, and thus the connection
results_proxy.____
# Print the count by state
print(state_count)