[Tutor] database help for newbie, fetchall()

Python python at venix.com
Mon Jun 26 17:16:29 CEST 2006


On Sun, 2006-06-25 at 20:14 -0400, Rene Bourgoin wrote:
> 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,)]. 
Correct

> 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. 
The python sql module will have converted the data items into Python
data types.  That is usually preferable.  If you really need all of your
data as strings, your code could look something like:

def strcols(cursor):
	for row in cursor.fetchall():
		yield [str(col) for col in row]
...
for cols in strcols(cursor):
	# cols will be a list of row values converted to strings
	# do what needs to be done
...

> Even if you loop through the list you are left with a tuple that represents each column. (aa,bbb,x,ccc)
> Then you need to loop through the tuple to get your data into strings to use in your app some where.
> It seems to be more steps then it should be.
> Is there a cleaner way to do this?

You'll need to decide if that is cleaner than your current code.  If you
want named access to the column values, some of the Python database
packages (such as MySQLdb) can be configured to return the rows as
dictionaries rather than tuples.  Also the strcols function could be
changed to yield a dictionary rather than a list.  The
cursor.description provides the column names, along with other data.

> 
> 
> 
> 
> _______________________________________________
> No banners. No pop-ups. No kidding.
> Make My Way  your home on the Web - http://www.myway.com
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp



More information about the Tutor mailing list