[Tutor] database help for newbie, fetchall()

Alan Gauld alan.gauld at freenet.co.uk
Mon Jun 26 18:25:52 CEST 2006

> What is the best way to handle the resutls to a fetchall() command?
> The result seems to be a list of tuples 
> [(aaa,bbb,ccc0,(11,222,333,)].

Yes, thats usually the most convenient way to present groups of data.

> I'm new to programming but it seems that what ever I try to 
> accomplish
> at some point i need the results to end up as strings.

Thats pretty unusual. Usually strings are only needed for display
(other than where the data is a string by default - eg a name!)
Mostly its moire convenient to treat numbers as numbers,
dates as dates, money as money etc and only turn them into
strings for display purposes - which is where the format string
operator comes into its own.

> Even if you loop through the list you are left with a tuple that
> represents each column. (aa,bbb,x,ccc)

Correct and you can extract each item using indexing:

for group in result:
  myDate = group[0]
  myCash = group[3]
  myString = group[2]

> Then you need to loop through the tuple to get your data into 
> strings
> to use in your app some where.

Why do you need to convert to strings? If the data is string data it
should still be string data when you extract it. If its not string 
why do you need to convert it? Other than for display, and that can
be done in one line, like:

displayString = "%s\t%0.2f\t%s" % (myDate, myCash,myString)

> It seems to be more steps then it should be.
> Is there a cleaner way to do this?

The question is probably more about why you feel the need for strings?

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list