[Tutor] tuples and mysqldb tables
Ed Hotchkiss
edhotchkiss at gmail.com
Sun Sep 18 23:53:40 CEST 2005
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 <http://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)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050918/e4fc233b/attachment.htm
More information about the Tutor
mailing list