pythonmysqldatabase

Loop through Mysql Results


This is the code I have:

r = ''
while True:
    data = result.fetch_row()
    r+= record[0][0] + record[0][1] + record[0][0]
print r

What I want to do is, first fetch all the rows:

data = result.fetch_row(0)

and then run a loop for "data"

rather than do it within the while loop.


Solution

  • You can loop over the cursor itself:

    for row in result:
        # do something with row
    

    Iteration over cursors is optional in the Python DB-API 2 specification, but in practice all current implementations support it.

    This gives the database adapter the freedom to fetch rows from the database server in batches, as needed.

    If you do stumble on a database adapter that doesn't support iteration over a cursor, then you can always fall back to cursor.fetchall():

    for row in cursor.fetchall():
        # do something with row
    

    However, take into account that this'll load the whole result set into a list.