# L-34 MCS 275 Wed 9 Apr 2008 : tempdbqueries.py

# Performs some queries on the table inputdata 
# of the database temperatures.

import MySQLdb

def PrintRecords(R):
   """
   Prints all records in R to screen.
   """
   for r in R:
      print r[1],str(r[2]), str(r[3]),':',r[4]

def ShowAll(c):
   """
   Shows all data to screen.
   """
   q = 'select * from inputdata'
   c.execute(q)
   R = c.fetchall()
   PrintRecords(R)

def ShowChicago(c):
   """
   Shows date, time and temperatures
   recorded in Chicago.
   """
   q = 'select d,t,temp from inputdata' \
     + ' where p = \"Chicago\"'
   c.execute(q)
   R = c.fetchall()
   for r in R:
      print str(r[0]), str(r[1]),':',r[2]

def ShowSorted(c):
   """
   Shows all records sorted by temperature
   in descending order.
   """
   q = 'select * from inputdata order by' \
     + ' temp desc'
   c.execute(q)
   R = c.fetchall()
   PrintRecords(R)

def main():
   """
   Connects to the database temperatures,
   creates a cursor and executes some queries.
   """
   db = MySQLdb.connect(db="temperatures")
   cr = db.cursor()
   print 'all records in inputdata table'
   ShowAll(cr)
   print 'temperatures recorded in Chicago'
   ShowChicago(cr)
   print 'sorted by temperature, descending'
   ShowSorted(cr)

if __name__=="__main__": main()
