[DB-SIG] fetchone() as fetchall()

Hrvoje Niksic hniksic@iskon.hr
24 Dec 1999 13:33:05 +0100


I've often found fetchall() convenient to use simply because I could
write something like:

for entid, userid in cursor.fetchall():
  ...

The same thing written with fetchone() would look like this:

while 1:
  row = cursor.fetchone()
  if row is None:
    break
  entid, userid = row
  ...

That's *five* lines of code replacing one line.  However, when
retrieving large datasets, especially in long-running programs, using
fetchall() is often not acceptable.  Here is a small wrapper class
that enables you to use fetchone() as if it were fetchall.  It is
quite trivial, but I'd still like to contribute it to whoever might be
interested.

class FetchAll:
    def __init__(self, cursor):
        self.__cursor = cursor
    def __getitem__(self, index):
        # The indices had better be in order, because we're not
        # wasting time checking them.
        result = self.__cursor.fetchone()
        if result is not None:
            return result
        else:
            raise IndexError

Given the above example, the usage looks like this:

for entid, userid in FetchAll(cursor):
  ...

Feel free to incorporate the class in your programs.  I hope someone
finds it useful.