Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About mysql cursor and iterator

Tags:

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     ..... 

But this doesn't look good, so I wonder whether this way works as imagined:

for row in 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?

like image 787
taijirobot2 Avatar asked Jun 01 '11 03:06

taijirobot2


People also ask

What is a MySQL cursor?

MySQL cursor is a kind of loop facility given to traverse in the result of SQL one by one. We can operate on every result by using the cursor in MySQL. Cursors are supported in stored procedures, functions, and triggers only. MySQL cursor is available from version 5 or greater.

How many types of cursors are there in MySQL?

MySQL supports cursors inside stored programs. The syntax is as in embedded SQL.

How do I iterate through a cursor?

Initially cursor is not on the first row show using moveToNext() you can iterate the cursor when record is not exist then it return false ,unless it return true , while (cursor. moveToNext()) { ... }

How do I loop a cursor in MySQL?

They help you execute a specific sequence of instructions repeatedly until a particular condition breaks the loop. MySQL also provides a way to execute instructions on individual rows using cursors. Cursors in MySQL will execute a set of instructions on rows returned from SQL queries.


1 Answers

The MySQLdb cursor class implements the iterator protocol, so you can simply do this:

cursor.execute(sql) for row in cursor:     print row     ... 

Relevant code from MySQLdb.cursors.BaseCursor:

def __iter__(self):     return iter(self.fetchone, None) 
like image 199
samplebias Avatar answered Oct 11 '22 10:10

samplebias