레코드를 블록 단위로 처리하기
지금까지 정말 잘하셨어요! 동영상에서 Jason이 설명했듯이, 큰 ResultProxy를 다뤄야 할 때가 있고, 모든 결과를 한꺼번에 메모리에 올릴 수 없을 수도 있어요. 이 문제를 피하려면 루프 안에서 .fetchmany() 메서드를 사용해 ResultProxy에서 행을 블록 단위로 가져오면 됩니다. .fetchmany()에는 가져올 레코드 수를 인수로 전달하세요. 빈 리스트에 도달하면 더 이상 가져올 행이 없다는 뜻이므로 쿼리의 모든 결과를 처리한 것입니다. 그런 다음 .close() 메서드를 사용해 데이터베이스 연결을 닫아야 합니다.
이제 미리 로드해 둔 큰 ResultProxy인 results_proxy를 사용해 이를 직접 연습해 볼까요.
이 연습은 강의의 일부입니다
Python으로 배우는 데이터베이스 입문
연습 안내
more_results가 있는지 확인하는while루프를 사용하세요.- 루프 안에서
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)