按批处理记录
到目前为止做得非常好!正如 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)