【发布时间】:2013-07-17 18:17:51
【问题描述】:
我正在尝试使用 pyodbc 处理一个非常大的查询,我需要遍历这些行,而不是使用 fetchall() 一次性加载它们。
有没有一种好的和有原则的方法来做到这一点?
【问题讨论】:
-
我觉得你也可以
for row in cursor:
我正在尝试使用 pyodbc 处理一个非常大的查询,我需要遍历这些行,而不是使用 fetchall() 一次性加载它们。
有没有一种好的和有原则的方法来做到这一点?
【问题讨论】:
for row in cursor:
当然 - 使用 while 循环和 fetchone。
http://code.google.com/p/pyodbc/wiki/Cursor#fetchone
row = cursor.fetchone()
while row is not None:
# do something
row = cursor.fetchone()
【讨论】:
for row in cursor: 循环
根据official documentation,游标显然是一个迭代器。因此,您不需要创建自定义迭代器/生成器。
如果您要一次处理一行,可以将游标本身用作迭代器:
cursor.execute("select user_id, user_name from users"):
for row in cursor:
print(row.user_id, row.user_name)
【讨论】:
如果你想批量获取,你也可以使用cursor.fetchmany()(如果你不覆盖它,默认为 1)
【讨论】: