tuples and mysqldb tables

Python python at venix.com
Mon Sep 19 15:43:50 CEST 2005


I believe that the current version of MySQLdb supports:
for row in cursor:
	id, protocol, name, description = row

fall back on:
for row in cursor.fetchall():

if the first suggestion fails.

I'm not sure that this is clear from the DBI documentation.

On Sun, 2005-09-18 at 17:53 -0400, Ed Hotchkiss wrote:
> I have used fetchall() to insert the values from a table into a tuple.
> anywhere from 0 - ? many rows could be in this tuple, so it is a row
> within a row. How do I use a loops to iterate through the nested
> tuple, and assign the tuples integers and strings to variables, ugh :P
>  
> The Tables data is like this: 
>  
> +---------------------------------------------------------------------------------------------------------------------+
> |    ID (INT)  |   Protocol (TEXT)  |  Name (LONGTEXT)  Description
> (LONGTEXT)     |   
> +---------------------------------------------------------------------------------------------------------------------+
>  
>  
> 
>  
> 
> import MySQLdb
> 
> import sys
> 
>  
> 
> # find out what this ports function is ----
> 
> def grabPortInfo(port):
> 
> try:
> 
> conn=MySQLdb.connect( host="www.freesql.org",
> 
> user="portnumbers",
> 
> port=3306,
> 
> passwd="*********",
> 
> db="portnumbers")
> 
> except MySQLdb.Error, e: 
> 
> print "Error %d: %s" % (e.args[0], e.args[1]) 
> 
> print "\n\n WTF!? - portnumbers MySQL DB didn't open"
> 
> sys.exit (1)
> 
> # ------------------
> 
> cursor = conn.cursor()
> 
> stmt = "SELECT * FROM portnumbers WHERE port=%i" %port
> 
> cursor.execute(stmt)
> 
> numrows = int(cursor.rowcount)
> 
> if numrows == 0:
> 
> print "port # not found in database"
> 
> elif numrows >= 1:
> 
> result = cursor.fetchall()
> 
> print len(result)
> 
> # break tuple into strings with output 
> 
> myPort = port
> 
> myProtocol = result[0|3]
> 
> myName = result[0|4]
> 
> myDescription = result[0|5]
> 
> print "PORT # | PROTOCOL | PORT NAME | PORT DESCRIPTION "
> 
> print myPort, myProtocol, myName, myDescription
> 
> cursor.close()
> 
> conn.close()
> 
> # end function -------------
> 
>  
> 
> grabPortInfo(22)
> 
>  
> 
>  
> 

-- 
Lloyd Kvam
Venix Corp




More information about the Python-list mailing list