Saturday, July 14, 2012

Added SQLite 3 to my Gas calc program.

I updated my gas miles program, and it now Stores data to an SQLite3 database.

from Tkinter import *
import tkMessageBox
import sqlite3

def createdb():
    #Create a database if it does not exist.
##    conn=sqlite3.connect('mygasmiles.db')
    conn=sqlite3.connect('mygasmilesTest.db')
    #Create a Cursor object
    cur=conn.cursor() 
    #Create a table using the cursor object
    cur.execute("CREATE TABLE IF NOT EXISTS mpgtable(gals real,odometer real,mpg real)")
     #Get data from GUI
    Gallons = float(gallons.get())
    Miles = float(odometer.get())
    mpg =round( float(Miles)/float(Gallons),2)
    tkMessageBox.showinfo("Gas miles", mpg)
    clearGUI()
    #Add data to table.
    cur.execute("INSERT INTO mpgtable values(?,?,?)",([Gallons,Miles,mpg]))
    conn.commit()
    listData()
def clearGUI():
    gallons.delete(0,END)
    odometer.delete(0,END)
   
def listData():
##    conn=sqlite3.connect("mygasmiles.db")
    conn=sqlite3.connect("mygasmilesTest.db")
    cur=conn.cursor()

    myrows=cur.execute("select * from mpgtable")
    for row in myrows:
         print'--------------------------------'
         print'Gallons =  ',row[0]
         print 'Odometer  = ',row[1]
         print'MPG = ',  row[2]
   
root = Tk()
aframe = Frame(root)
aframe.pack(side=RIGHT)

Label(aframe,text='Gallons used').pack()
gallons=Entry(aframe)
gallons.pack()

Label(aframe,text='Odometer miles').pack()
odometer=Entry(aframe)
odometer.pack()

btn =Button(aframe,text='calc',command=createdb)
btn.pack(side=LEFT)

btn2=Button(aframe,text='List table',command=listData)
btn2.pack(side=LEFT)
root.mainloop()

Followers

Blog Archive

About Me

My photo
Biking helps me to cope with life.