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

# Given data stored as dictionaries in a file "temperatures.txt",
# this scripts shows the data as tuples as they would be used for
# insertion in a MySQL table.

import MySQLdb

def DataTuples():
   """
   Returns a list of tuples for the
   data in the file temperatures.txt.
   """
   file = open('temperatures.txt','r')
   T = []
   key = 0
   while True:
      L = file.readline()
      if L == '': break
      d = eval(L)
      tp = (key,d['place'],d['date'],d['time'],d['temp'])
      T.append(tp)
      key = key + 1
   file.close()
   return T

def InsertCommands(T):
   """
   Given the list T of data tuples,
   returns the list of MySQL commands
   to insert the data in the table inputdata.
   """
   L = []
   for t in T:
      s = 'insert into inputdata values (' \
        + '\"' + str(t[0]) + '\",' \
        + '\"' + t[1] + '\",' \
        + '\"' + t[2] + '\",' \
        + '\"' + t[3] + '\",' \
        + '\"' + str(t[4]) + '\");'
      L.append(s)
   return L

def InsertData(L):
   """
   Executes the MySQL commands in L.
   """
   db = MySQLdb.connect(db="temperatures")
   cr = db.cursor()
   for c in L: 
      cr.execute(c)

def main():
   """
   Reads the data from temperatures.txt
   and inserts into the inputdata table
   of the database temperatures.
   """
   T = DataTuples()
   print T
   L = InsertCommands(T)
   print L
   InsertData(L)

if __name__=="__main__": main()
