[DB-SIG] reg cursor.fetchall()

Carsten Haese carsten at uniqsys.com
Wed Feb 8 15:07:32 CET 2006


On Tue, 2006-02-07 at 23:08, python eager wrote:
> Hi , This is my statment which will work fine. but the statment line
> is long. How to split up these lines . 
>  
> Code Snippet :
>  
> for PID,FIRSTNAME,MIDDLENAME,LASTNAME,
> MARITALSTATUS,EMPLOYEESTATUS,NOD,SALARY,
> POI,RADDRESS,OADDRESS,MNO,LNO,DOBD,DOBM,
> DOBY,DOID,DOIM,DOIY,DOED,DOEM,DOEY in cursor.fetchall():

You could split this up if you place parentheses around the tuple, but
it's probably not a good idea to pollute your namespace with a million
little column names like this. Also, if the set of columns in your query
changes, you'd have to change that for line as well.

An alternative is to define a class whose instances contain the column
values as attributes. Example:

class RowObject(object):
  def __init__(self, data, description):
    self.__dict__.update(dict(zip([col[0] for col in description], data)))  

for rowdata in cursor.fetchall():
  row = RowObject(rowdata, cursor.description)
  # now you can do stuff with row.PID, row.FIRSTNAME, or however the columns
  # in the query are named.

By the way, you might not have to fetch all rows and then loop over the
list that gets returned. Most DB-API modules allow you to iterate over
the cursor:

for rowdata in cursor:
  # do stuff

For large result sets this is more efficient because you only process
one row at a time instead of sucking the entire result set into one huge
list.

Hope this helps,

Carsten.



More information about the DB-SIG mailing list