Monday, August 24, 2020

tkinter & SQLite

from tkinter import *

import sqlite3


win = Tk()

win.title("SQLite Database with tkinter")

win.geometry("400x250")

S1, S2, S3, S4, S5 = StringVar(), StringVar(), StringVar(), StringVar(), StringVar()


def create():

  conn = sqlite3.connect('address_book.db')

  cur = conn.cursor()

  query = '''CREATE TABLE addresses(fname VARCHAR(15), lname VARCHAR(15), city VARCHAR(15), pin INT)'''

  cur.execute(query)

  conn.commit()

  conn.close()


def submit():

  conn = sqlite3.connect('address_book.db')

  fn, ln, ci, pi = entFName.get(), entLName.get(), entCity.get(), int(entPin.get())

  cur = conn.cursor()

  cur.execute('''INSERT INTO addresses(fname, lname, city, pin)

              VALUES(?, ?, ?, ?)''', (fn, ln, ci, pi))

  conn.commit()

  conn.close()

  entFName.delete(0, END)

  entLName.delete(0, END)

  entCity.delete(0, END)

  entPin.delete(0, END)


def display():

  conn = sqlite3.connect('address_book.db')

  cur = conn.cursor()

  cur.execute("SELECT oid, * FROM addresses")

  records = cur.fetchall()

  print_records = ''

  for record in records:

    print_records += str(record) + "\n"

  lblQuery.config(text=print_records)

  conn.commit()

  conn.close()


def delete():

  conn = sqlite3.connect('address_book.db')

  cur = conn.cursor()

  cur.execute("DELETE FROM addresses WHERE oid = " + entID.get())

  conn.commit()

  conn.close()


def update():

  conn = sqlite3.connect('address_book.db')

  cur = conn.cursor()

  cur.execute("SELECT * FROM addresses WHERE oid = " + entID.get())

  record = cur.fetchall()

  S1.set(record[0][0]);  S2.set(record[0][1])

  S3.set(record[0][2]);  S4.set(record[0][3])

  conn.commit()

  conn.close()


create()


lbl01    = Label(win, text="First Name").place(x=0, y=0)

entFName = Entry(win, width=20, textvariable=S1);  entFName.place(x=80, y=0)

lbl02    = Label(win, text="Last Name").place(x=0, y=30)

entLName = Entry(win, width=20, textvariable=S2);  entLName.place(x=80, y=30)

lbl03    = Label(win, text="City").place(x=0, y=60)

entCity  = Entry(win, width=20, textvariable=S3);  entCity.place(x=80, y=60)

lbl04    = Label(win, text="Pin Code").place(x=0, y=90)

entPin   = Entry(win, width=10, textvariable=S4);  entPin.place(x=80, y=90)


btnAdd = Button(win, text="Add Record", command=submit)

btnAdd.place(x=20, y=120)

btnShowAll = Button(win, text="Show All", command=display)

btnShowAll.place(x=120, y=120)

lblQuery = Label(win);  lblQuery.place(x=0, y=170)


S5.set("3")

entID = Entry(win, width=3, textvariable=S5);  entID.place(x=295, y=90)

btnDelete = Button(win, text="Delete", command=delete)

btnDelete.place(x=210, y=120)


btnUpdate = Button(win, text="Update Record", command=update)

btnUpdate.place(x=280, y=120)


win.mainloop()


No comments:

Post a Comment