[Tutor] Trying to use MySQLdb.cursor

Vicki Stanfield vicki at stanfield.net
Fri Mar 25 04:27:37 CET 2005


I finally gave up and used MySQLdb to connect to my database. It connects
okay, and returns data, but now I have a new question. I use the code
below to print the data returned from my query, but I would like to make
labels at the top of the columns. How do I do this dynamically? I would
like to get the fieldnames as defined by mysql and print them before
printing each column. Is there a way to do this?

Here is the relevant portion of the code:

def getdata():
     conn = MySQLdb.Connect(
         host='localhost', user='user',
         passwd='password', db='sample',compress=1,
         cursorclass=MySQLdb.cursors.DictCursor)
     cursor = conn.cursor()
     cursor.execute("""SELECT computers.comp_location FROM computers, mice
                WHERE mice.mouse_type = "USB"
                AND computers.comp_location like "A%"
                AND mice.mouse_comp = computers.comp_id;""")
     rows = cursor.fetchall()
     cursor.close()
     conn.close()

     print '''
     <table border="1" cellpadding="5">
     '''

     for row in rows:
          print "<tr>"
          for cell in row:
              print "<td> %s </td>" % row[cell]

          print "</tr>"

Thanks for helping me get going.
Vicki



More information about the Tutor mailing list