Use Generators For Fetching Large DB Record Sets
Use Generators For Fetching Large DB Record Sets
When using the python DB API, it's tempting to always use a cursor's fetchall()
method so that you can easily iterate through a result set. For very large result
sets though, this could be expensive in terms of memory (and time to wait for the
entire result set to come back). You can use fetchmany() instead, but then have to
manage looping through the intemediate result sets. Here's a generator that
simplifies that for you.
Python, 11 lines
1 # This code require Python 2.2.1 or later
2 from __future__ import generators # needs to be at the top of your module
3
4 def ResultIter(cursor, arraysize=1000):
5 'An iterator that uses fetchmany to keep memory usage down'
6 while True:
7 results = cursor.fetchmany(arraysize)
8 if not results:
9 break
10 for result in results:
11 yield result
To iterate through the result of a query, you often see code like this:
This is fine if fetchall() returns a small result set, but not so great if the query
result is very large, or takes a long time to return. 'very large' and 'long time' is
relative of course, but in any case it's easy to see that cursor.fetchall() is going to
need to allocate enough memory to store the entire result set in memory at once.
In addition, the doSomethingWith function isn't going to get called until that entire
query finishes as well.
...
# where con is a DB-API 2.0 database connection object
cursor = con.cursor()
cursor.execute('select * from HUGE_TABLE')
This looks similar to code above, but internally the ResultIter generator is chunking
the database calls into a series of fetchmany() calls. The default here is that a
1000 records at a time are fetched, but you can change that according to your own
requirements (either by changing the default, or just using the second parameter
to ResultIter(). As always, trying different values with the profiler is probably a
good idea...performance could vary based on schema, database type, and/or
choice of python DB API 2.0 module.
Tags: database