In this article, we are going to make a simple project on a boutique management system using Python MySql connectivity.
Introduction
This is a boutique management system made using MySQL connectivity with Python. It uses a MySQL database to store data in the form of tables and to maintain a proper record of all details. Different SQL queries that include DDL, DQL, DML, and DCL commands are used in this project which is useful to perform CRUD (Create, Read, Update, Delete) operations using MySQL. This management system provides a common platform for customers, employees, as well employers to use the services. The various functionalities provided in this system are:
Customers: Customer can create their accounts, sign in to their accounts and perform various operations such as book their orders, view booking, delete bookings and update their details.
Employees: Employees can sign in to their account using their employee id and perform operations such as updating delivered orders of customers, adding a new product, and deleting a product.
Employer: The employer can perform two operations which are viewing product details and adding a new employee.
Prerequisites
MySQL should be installed on our system. Refer to this link to Download the MySQL installer. Once MySQL Server is installed properly, we can create databases and tables using MySQL commands in MySQL Command-Line-Client. MySQL Command Line Client is installed together with the MySQL Server, so you don’t need to download and install the MySQL client separately. To check whether you have the client program on your machine, go to search, and type “MySQL”. To access MySQL Server from the command-line client, open the program and enter the password after that, you will be able to use the client.
The tables used for this Boutique Management System are made using MySQL Command-Line-Client.
Note: Refer to this article to know more about how to create databases and tables.
Creating database
CREATE DATABASE sboutique;
USE sboutique;
Creating customer table
The customer table has 6 columns, which store customer ID, customer name, last name, customer's phone number, address of the customer, and products booked.
create table customer (
cust_id int(8) PRIMARY KEY,
c_nam varchar(30),
c_lnam varchar(30),
c_phno varchar(10),
c_adrs varchar(50),
bkd_pro varchar(40) );
Here cust_id is made the primary key because each customer is considered to be unique.
Creating employee table
The employee table has 5 columns which stores, employee ID, employee name, last name, phone number, and address.
create table employee (
emp_id char(3) PRIMARY KEY,
e_nam varchar(30),
e_lnam varchar(30),
e_phno varchar(10),
e_adrs varchar(30),);
Here employee ID is made the primary key because each employee is considered to be unique.
Creating products table
The products table has 4 columns with columns product number, product id, product price, and product stock.
create table products (
pro_num char(5),
pro_id char(10) PRIMARY KEY,
pro_price int(6),
pro_stk int(5) );
Here product ID is made as the primary key because each product in the database has a unique ID.
Let's insert some products into the products table.
INSERT INTO products VALUES
('1','KWPTP25',330,18),
('2','KWPTP30',450,30),
('3','KWPTP45',650,20),
('4','SSST025',850,10),
('5','SSST030',350,12);
These 5 records are now added to the table.
Let's check the description and contents in the table. Type the following command in MySQL Command-Line-Client.
Checking the table structure and data stored in the table
USE sboutique;
SHOW TABLES;
Tables in sboutique databaseDESC customer;
Structure of customer tableDESC employee;
Structure of employee tableDESC products;
Structure of products table
To view entered records in the table, execute the below command :
SELECT * FROM products;
Data in products table
Now the tables are created in the database. This database can be used to store create records, update values in tables, and delete records.
Getting Started
We need to make a connection between the MySQL database and Python so that the tables can be accessed using python IDE. For making a connection we need to install mysql-connector which can be done by writing the following command in the command prompt on Windows.
pip install mysql-connector-python
After installation of the mysql-connector, we can connect MySQL with Python which can be done by writing the following code.
Python3
# Importing mysql connector module
import mysql.connector
# Making MySQL connection object
mycon = mysql.connector.connect(
host='localhost', user='root',
password='password',
database='sboutique')
# Making MySQL cursor object
mycur = mycon.cursor()
In the above code, we have to enter our localhost address, port number, and password that we have set while installing MySQL workbench It will look like the below image after setup MySQL workbench also we have to enter the database name on which we worked on.
Database and Tables in Use :
The name of the MySQL Database used is "sboutique" and the following tables are used :
Functions in the program
1. Check() Function
This function is being used to return a list of IDs of all the customers in the boutique. At the time of a customer login or new customer, it is used to check if the customer with this ID already exists or not.
Python3
# To check if a customer of a given ID exists or not
def check():
# Query to select all customer IDs
# from the table
qry = 'select cust_id from customer;'
mycur.execute(qry)
''' Return a list where each element
in the list is a tuple
fetched from each record in table
Each tuple contains a single element
as only customer IDs are fetched
from cust_id column of each record'''
d = mycur.fetchall()
# To create a list of all customer IDs in the table
list_of_ids = []
for ids in d:
# A list of all customer IDs in table
list_of_ids.append(ids[0])
return list_of_ids
2. Function to create a new customer account
The customer account function asks customers to enter their customer ID and it checks if a customer with this ID already exists or not because customer ID is a primary key in the customer table in the database and the values entered in these columns must be unique. If the customer exists it displays a message, else it takes the customer's details and inserts the record in the customer table of the database.
Python3
# To create a new account for the customer
def cust_ac():
ask = 'Y'
list_of_ids = check()
while ask in 'yY':
custid = int(input('Enter your customer id... '))
# to check if a customer already exists with this ID
if custid in list_of_ids:
print('This Customer Id already exists....\
Try creating a new one')
else:
# Tuple to contain details of the customer
c_det = ()
cnam = input('First Name : ')
clnam = input('Last Name : ')
cphno = input('Phone Number : ')
cadrs = input('Your Address : ')
c_det = (custid, cnam, clnam, cphno, cadrs)
''' Values inserted in the table and default NULL value are
provided for booked product at the time of creation
of customer account '''
qry = 'insert into customer values(%s,%s,%s,%s,%s,NULL);'
# value of the fields to be entered with the query
val = c_det
mycur.execute(qry, val)
mycon.commit()
print('Customer details entered')
ask = input('Do you want to continue (Y/N) ')
if ask not in ('Yy'):
space()
break
3. Get booked products function
This function returns a list of products booked by a customer using the customer's ID. It is used in other functions to view or delete the booked orders of the customer.
Python3
# To select all booked products of
# a given customer from the table
def get_bkd_pro(cust_id):
qry = 'select bkd_pro from customer\
where cust_id=%s;'
mycur.execute(qry, (cust_id,))
bp = mycur.fetchone()
bkd_pro = bp[0]
return bkd_pro
4. Function for Customer Login
This function allows the customer to log in to their accounts. It first checks if a customer with entered ID exists or not, and then asks for the customer's choice to :
- View their booked products
- To view the products booked by customers, the get booked product function is used where customer ID is passed as an argument.
- It then checks if the customer has any bookings or not and then displays the result accordingly.
- If more than one product is booked, the product IDs are stored as a single value in the table separated by '_'. The fetched values are then split and printed.
- Book a new product
- To book a new product, the function asks the customer to enter the product ID and then checks if the product with the given ID exists in the products table or not. It then adds the product to the booked products column of the customer's table.
- If the customer already has a booked product, the new product ID is concatenated with the existing ID and again stored in the table.
- Update their existing details
- For the customer to update their account, the function displays the existing customer details and then asks them to enter the fields they want to update.
- Cancel booked products
- To cancel booked products the function asks for product ID and checks if it is booked or not and then deletes it accordingly.
Python3
def sign_in():
try:
ask = int(input('Enter customer ID to sign in : '))
# Using check function to check whether this account exists or not
list_of_ids = check()
if ask in list_of_ids:
while True:
print(''' Do you want to :
1) View Bookings
2) Book a product
3) Update Self Details
4) Cancel booked products
enter 'back' to exit ''')
# Take choice of the customer
ccc = input('enter choice - ')
if ccc == '1':
# Get booked product function is used where cutomer ID
# is passed as an argument
s = get_bkd_pro(ask)
# To check if the column has any value
if s is None or s == ' ':
print('you have not booked products yet')
else:
''' If more than one products are booked,
their IDs are stored as a single value
separated by '_' so we have to split the
string to print each product ID.'''
# d is a list containing product IDs
d = s.split('_')
print('Booked products')
for bkditems in d:
print(bkditems)
if ccc == '2':
# check if the product to be booked exists or not
qry = 'select pro_id from products;'
mycur.execute(qry)
pro_list = mycur.fetchall()
''' contains a list where each element is a tuple fetched
from each record, the tuple contains values in the
column named pro_nam from products table.'''
# empty list to store product IDs
list_of_products = []
for i in pro_list:
list_of_products.append(i[0])
# Take ID and quantity of product to be booked
pro_id = input('Enter the product id to book products : ')
# To add booked product in the column,we first
# need to check if it already contains a value in it
if pro_id in list_of_products:
# Customer ID is given as value along with
# query to fetch booked product for the given ID
qry = 'select bkd_pro from customer where cust_id=%s;'
mycur.execute(qry, (ask,))
pr = mycur.fetchone()
# prl is value fetched from table
prl = pr[0]
# When the column is empty the new product is to stored
if prl is None or prl == ' ':
qry = 'update customer set bkd_pro=%s where cust_id=%s;'
val = (pro_id+'_', ask)
mycur.execute(qry, val)
mycon.commit()
print('Your Product is booked !!')
''' If there already exists a value in bkd_pro column,
new value must be concatenated with the existing
one and again stored in the table'''
else:
prl1 = prl+pro_id
qry2 = 'update customer set bkd_pro=%s where cust_id=%s;'
# val2 is the new value containing all booked products
# to be stored in the column
val2 = (prl1+'_', ask)
mycur.execute(qry2, val2)
mycon.commit()
print('Your Product is booked !!')
else:
print('This product does not exists.\
Please write the correct product id!')
if ccc == '3':
qry = 'select cust_id,c_nam,c_lnam,c_phno,c_adrs\
from customer where cust_id =%s'
mycur.execute(qry, (ask,))
# clist contains list of all values fetched
# in the form of a tuple for this customer ID
clist = mycur.fetchone()
# list of fields to be updated
flds = ['Name', 'Last Name', 'Ph.No', 'Address']
dic = {}
print("Your existing record is :")
# The fetched details are stored in the form of key
# value pair in a dictionary
for i in range(4):
dic[flds[i]] = clist[i+1]
print(i+1, ' ', flds[i], ' : ', clist[i+1])
for i in range(len(clist)):
updtc = int(input('enter choice to update '))
upval = input('enter'+flds[updtc-1]+' ')
# Change the value corresponding to the required field
dic[flds[updtc-1]] = upval
yn = input(
'Do you want to update other details? y or n ')
if yn in 'Nn':
break
qry = 'update customer set c_nam=%s,c_lnam=%s,c_phno=%s,\
c_adrs=%s where cust_id=%s;'
updtl = tuple(dic.values())+(ask,)
# The value to be passed along with the query is a tuple
# containing updated details of the given customer ID
val = (updtl)
mycur.execute(qry, val)
mycon.commit()
print('Your details are updated ')
if ccc == '4':
try:
# To get the existing bookings
# Booked products in the table
bkd_pro = get_bkd_pro(ask)
print('Your Booking(s) : \n ', bkd_pro)
if bkd_pro is None or bkd_pro == ' ':
print('you have no bookings to cancel')
else:
cw = input("To cancel all products; enter A \nOR \
enter the product code to cancel : ")
if cw in 'Aa':
qry = 'update customer set bkd_pro=NULL\
where cust_id=%s'
mycur.execute(qry, (ask,))
mycon.commit()
print('All bookings deleted')
elif cw in bkd_pro:
# If more than one products entered,
# split them on the basis of '_'
# x is a list containing all booked products
x = (bkd_pro[0:-1]).split('_')
# Delete the required product ID
x.remove(cw)
updt_pro = ''
# Again concatenate each product ID
# in the list to store in the table
for item in x:
updt_pro = updt_pro+item+'_'
qry = 'update customer set bkd_pro=%s where cust_id=%s'
val = (updt_pro, ask)
mycur.execute(qry, val)
mycon.commit()
print('Booking Cancelled !')
except Exception:
print('Some problem in updating details.Try again')
if ccc.lower() == 'back':
print("Successfully logged out")
space()
break
else:
print('This Account does not exist. ')
except Exception:
print('Some error occurred. Try Again')
5. View Products function
This function fetches all existing products from the database and then displays them in the form of a table.
Python3
# To fetch values from all columns of
# product table to get product details
def view_pro():
qry = 'select * from products;'
mycur.execute(qry)
d = mycur.fetchall()
# contains list of all records
dic = {}
# Each record fetched is separated into a key value pair
# and stored in the dictionary where product ID is the key
for i in d:
dic[i[0]] = i[1:]
print('_'*80)
# Printing the dictionary in the form of a table
print("{:<17} {:<22} {:<23} {:<19}".format(
'Product id', 'Product name', 'Price', 'Stock'))
print('_'*80)
for k, v in dic.items():
a, b, c = v
print("{:<17} {:<22} {:<23} {:<19}".format(k, a, b, c))
print('_'*80)
6. Add Products Function
Add products function is used by the employees of the boutique to add new product details. It asks for a product number, product ID, price, and stock from the employee and enters a new record in the products table of the database.
Python3
# To add a new product in Products table
def addpro():
# Display list of products
view_pro()
n = int(input('Enter no of items to insert '))
for j in range(n):
# Initialize tuple to store
# product details.
t = ()
pronum = input("Product No. ")
proid = input('Product ID : ')
pprice = int(input('Price : '))
pstk = int(input('Stock : '))
t = (pronum, proid, pprice, pstk)
# Using MySql query
qry = 'insert into products values(%s,%s,%s,%s);'
val = t
mycur.execute(qry, val)
mycon.commit()
print("Product Added")
7. Delete Product Function
This function is used by the employees of the boutique to delete product details. It asks for the product ID and then deletes the record from the products table of the database.
Python3
# To delete a product from the table
def delpro():
view_pro()
delt = input("Enter ID of product to be deleted")
qry = 'delete from products where pro_id=%s;'
mycur.execute(qry, (delt,))
mycon.commit()
print("Product is deleted")
8. Function for employee login
This function is used for employees to login into their accounts. It allows employees to :
- Update the records of delivered products.
- Add a new product to the database
- Deletes a product from the database
Python3
# For Employee Login
def emp_sign_in():
try:
ask = input('Enter id to sign in to the account : ')
# To check if the employee with this ID exists or not.
qry = 'select emp_id from employee;'
mycur.execute(qry)
d = mycur.fetchall()
lis = []
for i in d:
lis.append(i[0])
if ask not in lis:
print('Enter the correct id')
else:
while True:
space()
ccc = input("1. Update delivered records\n
2. Add a New Product \n
3. Delete a product \n
Enter 'Back' to logout: ")
if ccc == '1':
cust_id = input('Enter customer id')
# Check if the customer has bookings or not
bkd_pro = get_bkd_pro(cust_id)
if bkd_pro is None or bkd_pro == ' ':
print('This customer has no bookings ')
else:
print('All booking(s): ', bkd_pro)
pro_id = input('Enter product code to\
remove the delivered product ')
# The product IDs are stored in the form of a
# single value separated by '_'.
if pro_id in bkd_pro:
x = (bkd_pro[0:-1]).split('_')
# Returns a list of all booked products,
# then remove the delivered product from list
x.remove(pro_id)
# Concatenate the existing products using '_'
updt_pro = ''
for i in x:
updt_pro = updt_pro+i+'_'
qry = 'update customer set bkd_pro=%s \
where cust_id=%s;'
val = (updt_pro, cust_id)
mycur.execute(qry, val)
mycon.commit()
print('Delivered product is removed\
from the database. ')
else:
print('enter the correct code')
elif ccc == '2':
addpro()
elif ccc == '3':
delpro()
elif ccc.lower() == 'back':
print("Successfully logged out ")
break
except Exception:
print('Give the correct input')
10. Add Employee Function
Add employee function allows the employer to add a new employee to the boutique and insert the records into the employee table of the database.
Python3
# To add employee details
def addemp():
qry = "select * from employee;"
mycur.execute(qry)
emp_list = mycur.fetchall()
print("List of Employees ")
for emp in emp_list:
print("Emp Id : ", emp[0], " Name : ", emp[1],
" Last Name : ", emp[2], " Phone No : ", emp[3])
ne = []
n = int(input('enter the no. of employees to add '))
for i in range(1, n+1):
t = ()
print('enter employee id ')
idd = int(input(str(i)+') '))
print('Name ')
nam = input(str(i)+') ')
print('Last name ')
lnam = input(str(i)+') ')
print('Contact no. ')
conno = int(input(str(i)+') '))
print('Address ')
adrs = input(str(i)+') ')
# A tuple containing details of an employee
t = (idd, nam, lnam, conno, adrs)
# List containing details of n number
# of employees to be added
ne = ne+[t, ]
qry = 'insert into employee values(%s,%s,%s,%s,%s);'
# A list containing details of each employee
# in the form of a tuple is to be passed along with the query
for i in range(len(ne)):
val = ne[i]
mycur.execute(qry, val)
mycon.commit()
print('All Employee details added. ')
space()
11. Function for employer login
This function is used for employer login and allows the employer to :
- View all products
- Add a new employee
Python3
# For employer login
def employer():
while True:
print()
print('''Enter Your Choice:
1)View Product Details
2)Add a New Employee
enter back to exit''')
ccc = input('Enter _____ ')
if ccc == '1':
view_pro()
if ccc == '2':
addemp()
if ccc.lower() == "back":
break
Main Program
The program first asks for a choice of the user to enter as a customer, employee, or employer and calls the respective functions for the functioning of the program.
Python3
print('WELCOME !')
# Running a infinite loop
while True:
print('''Are you a :
(A). Customer
(B). Employee
(C). Employer
enter e to exit ''')
ch = input('Enter - ')
try:
if ch in 'aA':
print(" 1. Create Account\n 2.Sign In into existing account")
choice = input('enter- ')
if choice == '1':
cust_ac()
elif choice == '2':
sign_in()
else:
print('Enter correct choice')
if ch in 'bB':
emp_sign_in()
if ch in 'cC':
employer()
elif ch.lower() == "e":
print("Thankyou for visiting !")
break
except Exception:
print('Give the right input')
space()
Complete Code:
Python3
# Import MySql Connector
import mysql.connector
# making MySQL connection object
mycon = mysql.connector.connect(
host='localhost', user='root',
password='password', database='sboutique')
# making MySQL cursor object
mycur = mycon.cursor()
# To provide blank spaces in the output
def space():
for i in range(1):
print()
# To check if a customer of a given ID exists or not
def check():
# query to select all customer IDs from the table
qry = 'select cust_id from customer;'
mycur.execute(qry)
''' a list where each element in the list is a tuple
fetched from each record in table
Each tuple contains a single element as only customer IDs are fetched
from cust_id column of each record '''
d = mycur.fetchall()
# to create a list of all customer IDs in the table
list_of_ids = []
for ids in d:
# a list of all customer IDs in table
list_of_ids.append(ids[0])
return list_of_ids
# To create a new account for the customer
def cust_ac():
ask = 'Y'
list_of_ids = check()
while ask in 'yY':
custid = int(input('Enter your customer id... '))
# to check if a customer already exists with this ID
if custid in list_of_ids:
print('This Customer Id already exists....\
Try creating a new one')
else:
# Tuple to contain details of the customer
c_det = ()
cnam = input('First Name : ')
clnam = input('Last Name : ')
cphno = input('Phone Number : ')
cadrs = input('Your Address : ')
c_det = (custid, cnam, clnam, cphno, cadrs)
''' Values inserted in the table and default NULL value are
provided for booked product at the time of creation
of customer account '''
qry = 'insert into customer values(%s,%s,%s,%s,%s,NULL);'
# value of the fields to be entered with the query
val = c_det
mycur.execute(qry, val)
mycon.commit()
print('Customer details entered')
ask = input('Do you want to continue (Y/N) ')
if ask not in ('Yy'):
space()
break
# To select all booked products of a given customer from the table
def get_bkd_pro(cust_id):
qry = 'select bkd_pro from customer where cust_id=%s;'
mycur.execute(qry, (cust_id,))
bp = mycur.fetchone()
bkd_pro = bp[0]
return bkd_pro
def sign_in():
try:
ask = int(input('Enter customer ID to sign in : '))
# Using check function to check whether this account exists or not
list_of_ids = check()
if ask in list_of_ids:
while True:
print(''' Do you want to :
1) View Bookings
2) Book a product
3) Update Self Details
4) Cancel booked products
enter 'back' to exit ''')
# Take choice of the customer
ccc = input('enter choice - ')
if ccc == '1':
# Get booked product function is used where cutomer ID
# is passed as an argument
s = get_bkd_pro(ask)
# To check if the column has any value
if s is None or s == ' ':
print('you have not booked products yet')
else:
''' If more than one products are booked,
their IDs are stored as a single value
separated by '_' so we have to split the
string to print each product ID.'''
# d is a list containing product IDs
d = s.split('_')
print('Booked products')
for bkditems in d:
print(bkditems)
if ccc == '2':
# check if the product to be booked exists or not
qry = 'select pro_id from products;'
mycur.execute(qry)
pro_list = mycur.fetchall()
''' contains a list where each element is a tuple fetched
from each record, the tuple contains values in the
column named pro_nam from products table.'''
# empty list to store product IDs
list_of_products = []
for i in pro_list:
list_of_products.append(i[0])
# Take ID and quantity of product to be booked
pro_id = input('Enter the product id to book products : ')
# To add booked product in the column,we first
# need to check if it already contains a value in it
if pro_id in list_of_products:
# Customer ID is given as value along with
# query to fetch booked product for the given ID
qry = 'select bkd_pro from customer where cust_id=%s;'
mycur.execute(qry, (ask,))
pr = mycur.fetchone()
# prl is value fetched from table
prl = pr[0]
# When the column is empty the new product is to stored
if prl is None or prl == ' ':
qry = 'update customer set bkd_pro=%s where cust_id=%s;'
val = (pro_id+'_', ask)
mycur.execute(qry, val)
mycon.commit()
print('Your Product is booked !!')
''' If there already exists a value in bkd_pro column,
new value must be concatenated with the existing
one and again stored in the table'''
else:
prl1 = prl+pro_id
qry2 = 'update customer set bkd_pro=%s where cust_id=%s;'
# val2 is the new value containing all booked products
# to be stored in the column
val2 = (prl1+'_', ask)
mycur.execute(qry2, val2)
mycon.commit()
print('Your Product is booked !!')
else:
print('This product does not exists.\
Please write the correct product id!')
if ccc == '3':
qry = 'select cust_id,c_nam,c_lnam,c_phno,c_adrs\
from customer where cust_id =%s'
mycur.execute(qry, (ask,))
# clist contains list of all values fetched
# in the form of a tuple for this customer ID
clist = mycur.fetchone()
# list of fields to be updated
flds = ['Name', 'Last Name', 'Ph.No', 'Address']
dic = {}
print("Your existing record is :")
# The fetched details are stored in the form of key
# value pair in a dictionary
for i in range(4):
dic[flds[i]] = clist[i+1]
print(i+1, ' ', flds[i], ' : ', clist[i+1])
for i in range(len(clist)):
updtc = int(input('enter choice to update '))
upval = input('enter'+flds[updtc-1]+' ')
# Change the value corresponding to the required field
dic[flds[updtc-1]] = upval
yn = input(
'Do you want to update other details? y or n ')
if yn in 'Nn':
break
qry = 'update customer set c_nam=%s,c_lnam=%s,c_phno=%s,\
c_adrs=%s where cust_id=%s;'
updtl = tuple(dic.values())+(ask,)
# The value to be passed along with the query is a tuple
# containing updated details of the given customer ID
val = (updtl)
mycur.execute(qry, val)
mycon.commit()
print('Your details are are updated ')
if ccc == '4':
try:
# To get the existing bookings
# Booked products in the table
bkd_pro = get_bkd_pro(ask)
print('Your Booking(s) : \n ', bkd_pro)
if bkd_pro is None or bkd_pro == ' ':
print('you have no bookings to cancel')
else:
cw = input("To cancel all products; enter A \nOR \
enter the product code to cancel : ")
if cw in 'Aa':
qry = 'update customer set bkd_pro=NULL\
where cust_id=%s'
mycur.execute(qry, (ask,))
mycon.commit()
print('All bookings deleted')
elif cw in bkd_pro:
# If more than one products entered,
# split them on the basis of '_'
# x is a list containing all booked products
x = (bkd_pro[0:-1]).split('_')
# Delete the required product ID
x.remove(cw)
updt_pro = ''
# Again concatenate each product ID
# in the list to store in the table
for item in x:
updt_pro = updt_pro+item+'_'
qry = 'update customer set bkd_pro=%s where cust_id=%s'
val = (updt_pro, ask)
mycur.execute(qry, val)
mycon.commit()
print('Booking Cancelled !')
except Exception:
print('Some problem in updating details.Try again')
if ccc.lower() == 'back':
print("Successfully logged out")
space()
break
else:
print('This Account does not exist. ')
except Exception:
print('Some error occurred. Try Again')
# To fetch values from all columns of
# product table to get product details
def view_pro():
qry = 'select * from products;'
mycur.execute(qry)
d = mycur.fetchall()
# contains list of all records
dic = {}
# Each record fetched is separated into a key value pair
# and stored in the dictionary where product ID is the key
for i in d:
dic[i[0]] = i[1:]
print('_'*80)
# Printing the dictionary in the form of a table
print("{:<17} {:<22} {:<23} {:<19}".format(
'Product id', 'Product name', 'Price', 'Stock'))
print('_'*80)
for k, v in dic.items():
a, b, c = v
print("{:<17} {:<22} {:<23} {:<19}".format(k, a, b, c))
print('_'*80)
# To add a new product in Products table
def addpro():
# Display list of products
view_pro()
n = int(input('Enter no of items to insert '))
for j in range(n):
# Initialize tuple to store
# product details.
t = ()
pronum = input("Product No. ")
proid = input('Product ID : ')
pprice = int(input('Price : '))
pstk = int(input('Stock : '))
t = (pronum, proid, pprice, pstk)
# Using MySql query
qry = 'insert into products values(%s,%s,%s,%s);'
val = t
mycur.execute(qry, val)
mycon.commit()
print("Product Added")
# To delete a product from the table
def delpro():
view_pro()
delt = input("Enter ID of product to be deleted")
qry = 'delete from products where pro_id=%s;'
mycur.execute(qry, (delt,))
mycon.commit()
print("Product is deleted")
# For Employee Login
def emp_sign_in():
try:
ask = input('Enter id to sign in to the account : ')
# To check if the employee with this ID exists or not.
qry = 'select emp_id from employee;'
mycur.execute(qry)
d = mycur.fetchall()
lis = []
for i in d:
lis.append(i[0])
if ask not in lis:
print('Enter the correct id')
else:
while True:
space()
ccc = input("1. Update delivered records\n
2. Add a New Product \n
3. Delete a product \n
Enter 'Back' to logout: ")
if ccc == '1':
cust_id = input('Enter customer id')
# Check if the customer has bookings or not
bkd_pro = get_bkd_pro(cust_id)
if bkd_pro is None or bkd_pro == ' ':
print('This customer has no bookings ')
else:
print('All booking(s): ', bkd_pro)
pro_id = input('Enter product code to\
remove the delivered product ')
# The product IDs are stored in the form of a
# single value separated by '_'.
if pro_id in bkd_pro:
x = (bkd_pro[0:-1]).split('_')
# Returns a list of all booked products,
# then remove the delivered product from list
x.remove(pro_id)
# Concatenate the existing products using '_'
updt_pro = ''
for i in x:
updt_pro = updt_pro+i+'_'
qry = 'update customer set bkd_pro=%s \
where cust_id=%s;'
val = (updt_pro, cust_id)
mycur.execute(qry, val)
mycon.commit()
print('Delivered product is removed\
from the database. ')
else:
print('enter the correct code')
elif ccc == '2':
addpro()
elif ccc == '3':
delpro()
elif ccc.lower() == 'back':
print("Successfully logged out ")
break
except Exception:
print('Give the correct input')
# To add employee details
def addemp():
qry = "select * from employee;"
mycur.execute(qry)
emp_list = mycur.fetchall()
print("List of Employees ")
for emp in emp_list:
print("Emp Id : ", emp[0], " Name : ", emp[1],
" Last Name : ", emp[2], " Phone No : ", emp[3])
ne = []
n = int(input('enter the no. of employees to add '))
for i in range(1, n+1):
t = ()
print('enter employee id ')
idd = int(input(str(i)+') '))
print('Name ')
nam = input(str(i)+') ')
print('Last name ')
lnam = input(str(i)+') ')
print('Contact no. ')
conno = int(input(str(i)+') '))
print('Address ')
adrs = input(str(i)+') ')
# A tuple containing details of an employee
t = (idd, nam, lnam, conno, adrs)
# List containing details of n number
# of employees to be added
ne = ne+[t, ]
qry = 'insert into employee values(%s,%s,%s,%s,%s);'
# A list containing details of each employee
# in the form of a tuple is to be passed along with the query
for i in range(len(ne)):
val = ne[i]
mycur.execute(qry, val)
mycon.commit()
print('All Employee details added. ')
space()
# For employer login
def employer():
while True:
print()
print('''Enter Your Choice:
1)View Product Details
2)Add a New Employee
enter back to exit''')
ccc = input('Enter _____ ')
if ccc == '1':
view_pro()
if ccc == '2':
addemp()
if ccc.lower() == "back":
break
print('WELCOME !')
# Running a infinite loop
while True:
print('''Are you a :
(A). Customer
(B). Employee
(C). Employer
enter e to exit ''')
ch = input('Enter - ')
try:
if ch in 'aA':
print(" 1. Create Account\n 2.Sign In into existing account")
choice = input('enter- ')
if choice == '1':
cust_ac()
elif choice == '2':
sign_in()
else:
print('Enter correct choice')
if ch in 'bB':
emp_sign_in()
if ch in 'cC':
employer()
elif ch.lower() == "e":
print("Thankyou for visiting !")
break
except Exception:
print('Give the right input')
space()
Output:
Let's view the records added to the database.
Records in the Tables after executing the program:
Customer table:
Employee table:
Product table:
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Fundamentals
Python IntroductionPython was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in PythonUnderstanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython's input() function
7 min read
Python VariablesIn Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Python OperatorsIn Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /,
6 min read
Python KeywordsKeywords in Python are reserved words that have special meanings and serve specific purposes in the language syntax. Python keywords cannot be used as the names of variables, functions, and classes or any other identifier. Getting List of all Python keywordsWe can also get all the keyword names usin
2 min read
Python Data TypesPython Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Conditional Statements in PythonConditional statements in Python are used to execute certain blocks of code based on specific conditions. These statements help control the flow of a program, making it behave differently in different situations.If Conditional Statement in PythonIf statement is the simplest form of a conditional sta
6 min read
Loops in Python - For, While and Nested LoopsLoops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). In this article, we will look at Python loops and understand their working with the help of examples. For Loop in PythonFor loops is used to iterate ov
9 min read
Python FunctionsPython Functions is a block of statements that does a specific task. The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over an
9 min read
Recursion in PythonRecursion involves a function calling itself directly or indirectly to solve a problem by breaking it down into simpler and more manageable parts. In Python, recursion is widely used for tasks that can be divided into identical subtasks.In Python, a recursive function is defined like any other funct
6 min read
Python Lambda FunctionsPython Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python. In the example, we defined a lambda function(u
6 min read
Python Data Structures
Python StringA string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.Pythons = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # update print(s1) # printOut
6 min read
Python ListsIn Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Python TuplesA tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
6 min read
Dictionaries in PythonPython dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to
7 min read
Python SetsPython set is an unordered collection of multiple items having different datatypes. In Python, sets are mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and can change.Creating a Set in PythonIn Python, the most basic and efficient method for creating
10 min read
Python ArraysLists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences:Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
9 min read
List Comprehension in PythonList comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.For example,
4 min read
Advanced Python
Python OOPs ConceptsObject Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. OOPs is a way of organizing code that uses objects and classes to represent real-world entities and their behavior. In OOPs, object has attributes thing th
11 min read
Python Exception HandlingPython Exception Handling handles errors that occur during the execution of a program. Exception handling allows to respond to the error, instead of crashing the running program. It enables you to catch and manage errors, making your code more robust and user-friendly. Let's look at an example:Handl
6 min read
File Handling in PythonFile handling refers to the process of performing operations on a file, such as creating, opening, reading, writing and closing it through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
4 min read
Python Database TutorialPython being a high-level language provides support for various databases. We can connect and run queries for a particular database using Python and without writing raw queries in the terminal or shell of that particular database, we just need to have that database installed in our system.A database
4 min read
Python MongoDB TutorialMongoDB is a popular NoSQL database designed to store and manage data flexibly and at scale. Unlike traditional relational databases that use tables and rows, MongoDB stores data as JSON-like documents using a format called BSON (Binary JSON). This document-oriented model makes it easy to handle com
2 min read
Python MySQLMySQL is a widely used open-source relational database for managing structured data. Integrating it with Python enables efficient data storage, retrieval and manipulation within applications. To work with MySQL in Python, we use MySQL Connector, a driver that enables seamless integration between the
9 min read
Python PackagesPython packages are a way to organize and structure code by grouping related modules into directories. A package is essentially a folder that contains an __init__.py file and one or more Python files (modules). This organization helps manage and reuse code effectively, especially in larger projects.
12 min read
Python ModulesPython Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work.In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we c
7 min read
Python DSA LibrariesData Structures and Algorithms (DSA) serve as the backbone for efficient problem-solving and software development. Python, known for its simplicity and versatility, offers a plethora of libraries and packages that facilitate the implementation of various DSA concepts. In this article, we'll delve in
15 min read
List of Python GUI Library and PackagesGraphical User Interfaces (GUIs) play a pivotal role in enhancing user interaction and experience. Python, known for its simplicity and versatility, has evolved into a prominent choice for building GUI applications. With the advent of Python 3, developers have been equipped with lots of tools and li
11 min read
Data Science with Python
NumPy Tutorial - Python LibraryNumPy (short for Numerical Python ) is one of the most fundamental libraries in Python for scientific computing. It provides support for large, multi-dimensional arrays and matrices along with a collection of mathematical functions to operate on arrays.At its core it introduces the ndarray (n-dimens
3 min read
Pandas TutorialPandas is an open-source software library designed for data manipulation and analysis. It provides data structures like series and DataFrames to easily clean, transform and analyze large datasets and integrates with other Python libraries, such as NumPy and Matplotlib. It offers functions for data t
6 min read
Matplotlib TutorialMatplotlib is an open-source visualization library for the Python programming language, widely used for creating static, animated and interactive plots. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, Qt, GTK and wxPython. It
5 min read
Python Seaborn TutorialSeaborn is a library mostly used for statistical plotting in Python. It is built on top of Matplotlib and provides beautiful default styles and color palettes to make statistical plots more attractive.In this tutorial, we will learn about Python Seaborn from basics to advance using a huge dataset of
15+ min read
StatsModel Library- TutorialStatsmodels is a useful Python library for doing statistics and hypothesis testing. It provides tools for fitting various statistical models, performing tests and analyzing data. It is especially used for tasks in data science ,economics and other fields where understanding data is important. It is
4 min read
Learning Model Building in Scikit-learnBuilding machine learning models from scratch can be complex and time-consuming. Scikit-learn which is an open-source Python library which helps in making machine learning more accessible. It provides a straightforward, consistent interface for a variety of tasks like classification, regression, clu
8 min read
TensorFlow TutorialTensorFlow is an open-source machine-learning framework developed by Google. It is written in Python, making it accessible and easy to understand. It is designed to build and train machine learning (ML) and deep learning models. It is highly scalable for both research and production.It supports CPUs
2 min read
PyTorch TutorialPyTorch is an open-source deep learning framework designed to simplify the process of building neural networks and machine learning models. With its dynamic computation graph, PyTorch allows developers to modify the networkâs behavior in real-time, making it an excellent choice for both beginners an
7 min read
Web Development with Python
Flask TutorialFlask is a lightweight and powerful web framework for Python. Itâs often called a "micro-framework" because it provides the essentials for web development without unnecessary complexity. Unlike Django, which comes with built-in features like authentication and an admin panel, Flask keeps things mini
8 min read
Django Tutorial | Learn Django FrameworkDjango is a Python framework that simplifies web development by handling complex tasks for you. It follows the "Don't Repeat Yourself" (DRY) principle, promoting reusable components and making development faster. With built-in features like user authentication, database connections, and CRUD operati
10 min read
Django ORM - Inserting, Updating & Deleting DataDjango's Object-Relational Mapping (ORM) is one of the key features that simplifies interaction with the database. It allows developers to define their database schema in Python classes and manage data without writing raw SQL queries. The Django ORM bridges the gap between Python objects and databas
4 min read
Templating With Jinja2 in FlaskFlask is a lightweight WSGI framework that is built on Python programming. WSGI simply means Web Server Gateway Interface. Flask is widely used as a backend to develop a fully-fledged Website. And to make a sure website, templating is very important. Flask is supported by inbuilt template support na
6 min read
Django TemplatesTemplates are the third and most important part of Django's MVT Structure. A Django template is basically an HTML file that can also include CSS and JavaScript. The Django framework uses these templates to dynamically generate web pages that users interact with. Since Django primarily handles the ba
7 min read
Python | Build a REST API using FlaskPrerequisite: Introduction to Rest API REST stands for REpresentational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Fla
3 min read
How to Create a basic API using Django Rest Framework ?Django REST Framework (DRF) is a powerful extension of Django that helps you build APIs quickly and easily. It simplifies exposing your Django models as RESTfulAPIs, which can be consumed by frontend apps, mobile clients or other services.Before creating an API, there are three main steps to underst
4 min read
Python Practice
Python QuizThese Python quiz questions are designed to help you become more familiar with Python and test your knowledge across various topics. From Python basics to advanced concepts, these topic-specific quizzes offer a comprehensive way to practice and assess your understanding of Python concepts. These Pyt
3 min read
Python Coding Practice ProblemsThis collection of Python coding practice problems is designed to help you improve your overall programming skills in Python.The links below lead to different topic pages, each containing coding problems, and this page also includes links to quizzes. You need to log in first to write your code. Your
1 min read
Python Interview Questions and AnswersPython is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read