Skip to content

Instantly share code, notes, and snippets.

@robcowie
Created February 7, 2011 16:05
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save robcowie/814599 to your computer and use it in GitHub Desktop.
Save robcowie/814599 to your computer and use it in GitHub Desktop.
Memory-efficient, streaming query generator with MySQLdb
from MySQLdb.cursors import SSDictCursor
def iterate_query(query, connection, arraysize=1):
c = connection.cursor(cursorclass=SSDictCursor)
c.execute(query)
while True:
nextrows = c.fetchmany(arraysize)
if not nextrows:
break
for row in nextrows:
yield row
c.close()
results = iterate_query(SQL, conn, arraysize=100)
for row_dict in results:
print row_dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment