レコードをブロックごとに処理する
ここまで素晴らしいです!動画で Jason が述べたように、大きな ResultProxy を扱う必要がある一方で、結果を一度にすべてメモリに読み込めないことがあります。その場合の回避策として、ループ内で .fetchmany() メソッドを使って、ResultProxy から行をブロック単位で取得できます。.fetchmany() には、取得したいレコード数を引数として渡します。空のリストが返ってきたら、取得できる行はもう残っておらず、クエリ結果の処理が完了したことを意味します。最後に、.close() メソッドでデータベースへの接続を閉じる必要があります。
これから、事前に用意された大きな ResultProxy results_proxy を使って、この手法を練習していきます。
この演習はコースの一部です
Pythonで学ぶデータベース入門
演習の手順
more_resultsがあるかを確認するwhileループを使います。- ループ内で、
results_proxyに対して.fetchmany()メソッドを適用し、1 回につき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)