关于mysql游标和迭代器 [英] About mysql cursor and iterator
问题描述
想象我有一个mysql游标和数据读取。数据量可能非常大,每次我想处理一行。
Imagine I have a mysql cursor and data read. The amount of data might be very big that I want to deal with one line each time.
一个简单直接的方式可能是这样:
An easy and straight forward way might be like this:
while True:
row = cursor.fetchone()
if not row: break
.....
但这看起来不太好,所以我不知道这种方式是否像想象的那样工作: p>
but this doesn't look good, so I wonder whether this way works as imagined:
for row in iter(cursor.fetchall())
我想知道的是:如果我使用 iter(cursor.fetchall())
方式,所有数据首先还是每次只取一行?
the thing I want to know is: if I use the iter(cursor.fetchall())
way, does it fetch all the data first or it just fetch one row at a time?
任何想法都可以使用。
thx
推荐答案
MySQLdb
cursor类实现迭代器协议,因此您只需执行以下操作:
The MySQLdb
cursor class implements the iterator protocol, so you can simply do this:
cursor.execute(sql)
for row in cursor:
print row
...
相关代码 MySQLdb.cursors.BaseCursor :
def __iter__(self):
return iter(self.fetchone, None)
这篇关于关于mysql游标和迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!