0% found this document useful (0 votes)
2 views

CS Project File

The document outlines a Python program for managing a MySQL database for a clothing store, including functions for creating, modifying, and displaying tables. It features a main menu for user interaction, submenus for table management, and various functions for altering table structures and displaying records. The program also includes error handling for database operations and prompts for user input to guide the management of the database.

Uploaded by

Sanyam Bothra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CS Project File

The document outlines a Python program for managing a MySQL database for a clothing store, including functions for creating, modifying, and displaying tables. It features a main menu for user interaction, submenus for table management, and various functions for altering table structures and displaying records. The program also includes error handling for database operations and prompts for user input to guide the management of the database.

Uploaded by

Sanyam Bothra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

#SNK CLOTHING STORE DATABASE

#Modules

import mysql.connector as sql

pas = "benihime09"

#Required Functions

#1. Main Menu

def menu():

l = ["Create Table", "Manage Table", "Delete Table", "Display From Different Tables", "Exit"]

print("-----------------------------------------------------------------\nMain Menu")

for i in range(len(l)):

print(str(i+1)+ ". " + l[i])

print("-----------------------------------------------------------------")

#2. Table Menu

def sbmenu():

l = ["Modify Attributes", "Show Records", "Insert Record", "Update Record", "Delete Record",
"Exit"]

print("-----------------------------------------------------------------\n\nWhat do you wish to do")

for i in range(len(l)):

print(str(i+1)+ ". " + l[i])

print("-----------------------------------------------------------------\n")

#3. Alter Menu

def altmenu():

l = ["Add Column", "Modify Column", "Delete Column", "Exit"]

print("-----------------------------------------------------------------\nUpdate Table Menu")

for i in range(len(l)):

print(str(i+1)+ ". " + l[i])

print("-----------------------------------------------------------------\nWhat do you wish to do?")


#4. Display Menu

def dispmenu():

l = ["Display all", "Display all in order", "Display specific", "Display specific in order"]

print("-----------------------------------------------------------------\nDisplay Menu")

for i in range(len(l)):

print(str(i+1)+ ". " + l[i])

print("-----------------------------------------------------------------")

#5. Modify Menu

def modmenu():

l = ["Rename", "Change Data Type", "Set Primary Key", "Exit"]

print("\n-----------------------------------------------------------------\nWhat do you wish to do?")

for i in range(len(l)):

print(str(i+1)+ ". " + l[i])

print("-----------------------------------------------------------------")

#6. Check for existing table

def chk_tb(tb):

cur.execute("show tables;")

tblst = cur.fetchall()

for i in range(len(tblst)):

if tb == tblst[i][0]:

return True

else:

return False

#7. Show Existing Tables

def shw_tb():

que = "show tables;"

cur.execute(que)
tblst = cur.fetchall()

print("Available Tables:")

for i in range(len(tblst)):

print(str(i+1)+"." ,tblst[i][0])

#8. Create a Table

def cr_tb(tb):

try:

n = int(input("Enter number of attributes: "))

except Exception as err:

print("Error!!!")

print(err)

else:

que = "create table " + tb + "("

for i in range(n):

name = input("\nEnter attribute name: ")

dat = input("Enter datatype with length: ")

par = input("Enter constraints: ")

lst = [name, dat, par]

if i != n-1:

que += name + " " + dat + " " + par + ", "

continue

else:

que += name + " " + dat + " " + par + ");"

continue

try:

cur.execute(que)

except Exception as err:


print("ERROR!!")

pc.rollback()

print(err)

else:

print("\nTable Created!!")

pc.commit()

#9. Display

def dis():

lst = []

col = cur.column_names

rec = cur.fetchall()

for i in rec:

d = {}

for j in range(len(col)):

d[col[j]] = i[j]

print(d)

lst.append(d)

continue

return lst

#10. Get Column Names

def colnam(tb):

cur.execute("select * from "+ tb + ";")

r = cur.fetchall()

col = cur.column_names

cols = list(col)

return cols

#11. Display Coloumn Names


def colprint(cols, chcklst, dic):

print("-----------------------------------------------------------------\nAvailable Columns:")

for i in range(len(cols)):

chcklst.append(str(i+1))

dic[i+1] = cols[i]

print(str(i+1)+". "+cols[i])

print(f"{int(chcklst[-1])+1}. Exit\n-----------------------------------------------------------------")

#12. Correct Values

def corr(lst):

c=0

for i in range(len(lst)):

c += 1

if lst[i] in ("", " "):

lst[i] = "Null"

return lst

#######################################################

#Main

try:

import mysql.connector as sql

pc = sql.connect(user = "root", database = "SNKStore", host = "localhost", password = pas)

except Exception as err:

print("\n"*30+"Not Connecting")

print(err)

else:

cur = pc.cursor()

print("Welcome to SNK Store")


run = True

while run:

menu()

shw_tb()

choi = input("\n-----------------------------------------------------------------\nEnter option (1-5): ")

#Creating Table

if choi == "1":

tb = input("Enter Table Name: ")

if chk_tb(tb):

c=0

print("TABLE ALREADY EXISTS WITH GIVEN NAME!!!")

else:

cr_tb(tb)

#Manage Table

elif choi == "2":

tab = input("What table do you wish to access: ")

tbchk = chk_tb(tab)

if tbchk:

while tbchk:

sbmenu()

sbchoi = input("\n-----------------------------------------------------------------\nEnter option (1-6):


")

##Alter Table

if sbchoi == "1":

rundis = True
while rundis:

altmenu()

altchoi = input("Enter Option(1-4): ")

###Adding Column

if altchoi == "1":

colst = colnam(tab)

chklst = []

d = {}

print("-----------------------------------------------------------------\nAvailable Columns:")

for i in range(len(colst)):

chklst.append(str(i+1))

d[i+1] = colst[i]

print(str(i+1)+". "+colst[i])

print("\n-----------------------------------------------------------------")

ncolst = []

for i in colst:

x = i.lower()

ncolst.append(x)

name = input("\nEnter attribute name: ")

if name.lower() not in ncolst:

dat = input("Enter datatype with length: ")

par = input("Enter constraints: ")

if par.lower() != "primary key":

que = "alter table " + tab + " add (" + name + " " + dat + " " + par + ");"

cur = pc.cursor()

try:

cur.execute(que)
except Exception as err:

print("\nERROR!!\n"+err)

else:

print("\n\nColumn Successfully added!!\n")

else:

print("Primary key already exists!")

else:

print("\nColumn with given name already exists!!\n")

continue

###Modifying Column

if altchoi == "2":

colst = colnam(tab)

chklst = []

d = {}

runt = True

while runt:

print("\n")

colprint(colst, chklst, d)

colmod = input("Which column do you wish to modify?\nEnter Option(1-" +


str(int(chklst[-1])+1) + "): ")

if colmod in chklst:

modmenu()

cmd = input("Enter Option(1-4): ")


####Rename

if cmd == "1":

nnam = input("Enter a new name(Enter 0 to exit): ")

if nnam == "0":

continue

else:

rand = True

while rand:

print("Are you sure you wish to change from \'", d[int(colmod)], "\'
to \'", nnam, "\'?")

con = input("Yes or No(y/n): ")

if con.lower() == "y":

cur = pc.cursor()

try:

print("alter table " + tab + " rename column " + d[int(colmod)] + "
to " + nnam + ";")

cur.execute("alter table " + tab + " rename column " +


d[int(colmod)] + " to " + nnam + ";")

rand = False

runt = False

except Exception as err:

print("\nError!!\n"+err)

else:

print("Coloumn successfully changed")

elif con.lower() == "n":

print("\nAborting Renaming!!\n\n......\n......\nAborted!")

rand = False

runt = False

else:
print("Invalid Option Entered!")

####Change Data type

elif cmd == "2":

dat = input("Enter datatype with length: ")

que = "alter table " + tab + " modify column " + d[int(colmod)] + " " + dat +
";"

try:

cur = pc.cursor()

cur.execute(que)

runt = False

except Exception as err:

print("\nError!!\n"+err)

else:

print("\nColumn successfully modified")

continue

####Primary Key

elif cmd == "3":

cur = pc.cursor()

cur.execute("desc " + tab + ";")

attlst = cur.fetchall()

go = True

for i in attlst:

if i[3].lower() == "pri":

go = False

else:
continue

if go:

que = "alter table " + tab + " add primary key (" + d[int(colmod)] + ");"

try:

cur = pc.cursor()

cur.execute(que)

except Exception as err:

print("\nError!!\n"+err)

else:

print("\nPrimary Key successfully added")

else:

print("Following table already has a primary key!!")

continue

####Exitting the Menu

elif cmd == "4":

runt = False

continue

####Invalid Input Entered

else:

print("\nInvalid Command Entered\nEnter a valid option!\n")

continue

continue

####Exiting

elif colmod == str(int(chklst[-1])+1):


runt = False

continue

else:

print("\nInvalid Command Entered\nEnter a valid option")

continue

continue

###Deleting Column

if altchoi == "3":

colst = colnam(tab)

chklst = []

d = {}

colprint(colst, chklst, d)

col = input("Which coloumn do you wish to delete?\nEnter Option(1-" +


str(int(chklst[-1])+1) + "): ")

if col in chklst:

delcol = d[int(col)]

con = input("Are you sure, you wish to delete column \'"+ delcol.upper() + "\'\
nYes or No(y/n): ")

if con.lower() == "y":

cur = pc.cursor()

que = "alter table " + tab + " drop column " + delcol + ";"

try:

cur.execute(que)

except Exception as err:

print("\n\n"+err)

else:

print("\nColumn " + delcol + " was Successfully deleted!!\n")


elif con.lower() == "n":

print("\nAborting Deletion!!\n\n......\n......\nAborted!")

continue

else:

print("\n\nInvalid option entered!\nEnter a Valid option\n")

continue

###Exiting alter menu

if altchoi == "4":

rundis = False

continue

###Invalid Command Entered

else:

print("Invalid option entered!!\nEnter a Valid option!")

continue

##Display records

elif sbchoi == "2":

dispmenu()

dischoi = input("\nEnter option(1-4): ")

###Display all

if dischoi == "1":

cur.execute("select * from " + tab + ";")

disp = dis()

###Display all in order

elif dischoi == "2":


colst = colnam(tab)

d = {}

chklst = []

sel = True

colprint(colst, chklst, d)

while sel:

dispby = input(f"What column should it sort by?\nEnter Option(1-{len(colst)}): ")

if dispby in chklst:

while True:

orde = input("Ascending or Descending (A/D)")

if orde.lower() == "a":

orde = "asc"

sel = False

break

elif orde.lower() == "d":

orde = "desc"

sel = False

break

else:

print("\n\n\n\n\nInvalid Command\nEnter a valid Command")

continue

que = "select * from " + tab + " order by " + d[int(dispby)] + " " + orde + ";"

cur.execute(que)

disp = dis()
elif dispby == str(int(chklst[-1])+1):

sel = False

continue

else:

print("\n\nInvalid Option Entered!!\nEnter a valid Option")

###Display specific

elif dischoi == "3":

d = {}

chklst = []

cur = pc.cursor()

colst = colnam(tab)

colprint(colst, chklst, d)

sel = True

print("\nEnter the coloumns you want displayed\n(Exit to display)\n2")

coldlst = []

while sel:

coldisp = input(f"Enter option(1-{int(chklst[-1])+1}): ")

if coldisp in chklst:

coldlst.append(coldisp)

continue

elif coldisp == str(int(chklst[-1])+1):

sel = False
else:

print("\n\nInvalid Option Entered!!\nEnter a Valid Option")

cur = pc.cursor()

if len(coldlst) != 0:

que = "select "

for i in range(len(coldlst)):

que += d[int(coldlst[i])]

if i != len(coldlst)-1:

que += ", "

else:

que += " from " + tab + ";"

cur.execute(que)

disp = dis()

else:

continue

continue

###Display specific in order

elif dischoi == "4":

d = {}

chklst = []

cur = pc.cursor()

colst = colnam(tab)

colprint(colst, chklst, d)

sel = True

print("\nEnter the coloumns you want displayed\n(Exit to display)\n2")

coldlst = []
while sel:

coldisp = input(f"Enter option(1-{int(chklst[-1])+1}): ")

if coldisp in chklst:

coldlst.append(coldisp)

continue

elif coldisp == str(int(chklst[-1])+1):

sel = False

else:

print("\n\nInvalid Option Entered!!\nEnter a Valid Option")

cur = pc.cursor()

if len(coldlst) != 0:

que = "select "

for i in range(len(coldlst)):

que += d[int(coldlst[i])]

if i != len(coldlst)-1:

que += ", "

else:

que += " from " + tab + " order by "

sel = True

while sel:

dispby = input(f"What column should it sort by?\nEnter Option(1-{len(colst)}): ")

if dispby in chklst:

while True:

orde = input("Ascending or Descending (A/D)")

if orde.lower() == "a":

orde = "asc"
sel = False

break

elif orde.lower() == "d":

orde = "desc"

sel = False

break

else:

print("\n\n\n\n\nInvalid Command\nEnter a valid Command")

continue

else:

print("Invalid Option Entered!!\nEnter a valid option\n\n")

que += d[int(dispby)] + " " + orde + ";"

cur.execute(que)

disp = dis()

else:

continue

continue

###Invalid Input

else:

print("Invalid option entered!\nEnter a valid Option!")

continue

##Insert a record

elif sbchoi == "3":

reclst = []
que = "select * from " + tab + ";"

colst = colnam(tab)

print("For Date, use format yyyy-mm-dd")

for i in colst:

ent = input("Enter " + str(i) + " of record: ")

if ent != "":

if type(ent) == type("s4"):

entin = ent

else:

entin = eval(ent)

else:

entin = ent

reclst.append(entin)

cur = pc.cursor()

val = corr(reclst)

que = "insert into " + tab + " values('"

for i in val:

if i != val[-1]:

que += i + "', '"

else:

que += i + "');"

try:

cur.execute(que)

except Exception as err:

print("Error Occurred!\n"+err)

else:

print("Record Inserted!")
pc.commit()

continue

##Update the Record

elif sbchoi == "4":

cur = pc.cursor()

cur.execute("select * from " + tab + ";")

disp = dis()

cur = pc.cursor()

cur.execute("desc " + tab + ";")

attlst = cur.fetchall()

cur = pc.cursor()

colst = colnam(tab)

d = {}

chklst = []

colprint(colst, chklst, d)

cur = pc.cursor()

cur.execute("desc " + tab + ";")

attlst = cur.fetchall()

for i in attlst:

if i[3].lower() == "pri":

att = i[0]

break
upkno = input("\nEnter attribute you want to update\nEnter option(1-" + str(int(chklst[-
1])+1) + "): ")

if upkno in chklst:

upkey = d[int(upkno)]

idk = input("Enter the ID you want to change it for: ")

idlst = []

for i in disp:

idlst.append(i[att])

if idk in idlst:

for i in disp:

if i[att] == idk:

oval = i[upkey]

break

nval = input("Enter new value: ")

con = input("Are you sure, you wish to update record with " + att + " - \'" + idk +
"\'\nFrom \'" + str(oval) + "\' to \'" + str(nval) + "\'\nYes or No(y/n): ")

if con.lower() == "y":

cur = pc.cursor()

try:

if type(nval) == type("s4"):

cur.execute("update " + tab + " set " + upkey + "= \'" + nval + "\' where " + att
+ " = \'" + idk + "\';")

else:

nvalc = eval(nval)

cur.execute("update " + tab + " set " + upkey + " = " + nvalc + " where " + att
+ " = \'" + idk + "\';")

except Exception as err:


print(err)

else:

print("\n Record Successfully Updated!\n\n")

else:

print("\n\nInvalid!\nKey does not exist!!")

else:

print("\n\nInvalid Option Entered!")

continue

##Delete the Record

elif sbchoi == "5":

cur = pc.cursor()

cur.execute("select * from " + tab + ";")

disp = dis()

cur = pc.cursor()

cur.execute("desc " + tab + ";")

attlst = cur.fetchall()

for i in attlst:

if i[3].lower() == "pri":

att = i[0]

break

delkey = input("\nEnter " + att.upper() +" you want to delete: ")

attlst = []

for i in disp:

x = i[att]

attlst.append(x)
if delkey in attlst:

con = input("Are you sure, you wish to delete record with "+ att.upper() + " - \'"+
delkey +"\'\nYes or No(y/n): ")

if con.lower() == "y":

print("\nDeleting Record...")

que = "delete from " + tab + " where " + att + " = \'" + delkey + "\';"

try:

cur.execute(que)

print(que)

except Exception as err:

print("\nERROR!!")

print(err)

else:

print("\n......\nRecord Deleted")

break

elif con.lower() == "n":

print("\nAborting Deletion!!\n\n......\n......\nAborted!")

continue

else:

print("\nRecord with given " + att.upper() + " does not exist")

continue

##Exiting the sub-menu

elif sbchoi == "6":

tbchk = False

##Invalid Input
else:

print("Invalid Command Entered!!")

print("\n")

else:

print("TABLE WITH NAME DOES NOT EXIST")

continue

#Delete Table

elif choi == "3":

tab = input("Enter the name of table you want dropped: ")

if not(chk_tb(tab)):

print("\nTable does not exist!")

else:

while True:

con = input("\nAre you sure, you wish to delete table \'"+tab.upper()+"\'\n(*Data will not
be saved*)\nYes or No(y/n): ")

if con.lower() == "y":

print("\nDeleting Table...")

que = "drop table " + tab + ";"

try:

cur.execute(que)

except Exception as err:

print("\nERROR!!")

print(err)

else:

print("\n......\nTable Deleted")
break

elif con.lower() == "n":

print("\nAborting Deletion!!\n\n......\n......\nAborted!")

continue

#Display from Multiple Tables

elif choi == "4":

cur.execute("select SID, CName, sales.PID, PName, QTY, Price from stock, sales where sales.PID
= stock.PID;")

r = cur.fetchall()

coll = cur.column_names

colss = list(coll)

chlst = []

d = {}

print("-----------------------------------------------------------------\nAvailable Columns:")

for i in range(len(colss)):

chlst.append(str(i+1))

d[i+1] = colss[i]

print(str(i+1)+". "+colss[i])

print(f"{int(chlst[-1])+1}. Exit\n-----------------------------------------------------------------")

coldlst = []

sel = True

print("\nEnter the coloumns you want displayed\n(Enter 7 to exit)\n")

coldlst = []

while sel:

coldisp = input(f"Enter option(1-{int(chlst[-1])+1}): ")

if coldisp in chlst:
coldlst.append(coldisp)

continue

elif coldisp == str(int(chlst[-1])+1):

sel = False

else:

print("\n\nInvalid Option Entered!!\nEnter a Valid Option")

for i in range(len(d)):

if d[i+1] == "PID":

d[i+1] = "sales.PID"

else:

continue

que = "select "

for i in coldlst:

if i != coldlst[-1]:

que += d[int(i)] + ", "

else:

que += d[int(i)]

que += " from sales, stock where sales.PID = stock.PID;"

try:

cur = pc.cursor()

cur.execute(que)

except Exception as err:

print("\nERROR!\n" + err)

else:

print("\n\n-----------------------------------------------------------------\nData:\n")

l = dis()
print("\n-----------------------------------------------------------------\n")

continue

#Exiting

elif choi == "5":

run = False

print("\nThank You!")

#Invalid Input

else:

print("Invalid Command Entered!!")

print("Exiting!!\n\n")

You might also like