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:
JavaScript
x
5
1
while True:
2
row = cursor.fetchone()
3
if not row: break
4
..
5
But this doesn’t look good, so I wonder whether this way works as imagined:
JavaScript
1
2
1
for row in iter(cursor.fetchall())
2
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?
Advertisement
Answer
The MySQLdb
cursor class implements the iterator protocol, so you can simply do this:
JavaScript
1
5
1
cursor.execute(sql)
2
for row in cursor:
3
print row
4
5
Relevant code from MySQLdb.cursors.BaseCursor:
JavaScript
1
3
1
def __iter__(self):
2
return iter(self.fetchone, None)
3