Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 35

CONTENTS

1. Introduction
2. Requirements
3. About Project
4. Source code
5. Sample run
6. Suggestions for Improvement
7. Bibliography
INTRODUCTION
Connecting Python application with MySQL

1. Every application required data to be stored for future reference


to manipulate data. Today every application stores data in
database for this purpose.
2. Python allows us to connect all types of databases like Oracle,
SQL Server, MySQL.
3. Before we connect python program with any database like
MySQL we need to build a bridge to connect Python and MySQL.

To build this bridge so that data can travel both ways we need a
connector called “mysql.connector”.
We can install “mysql.connector” by using following methods:
At command prompt (Administrator login)
Type “pip install mysql.connector” and press enter
(internet connection in required)
This connector will work only for MySQL 5.7.3 or later
Or open “https://dev.mysql.com/downloads/connector/python/”
and download connector as per OS and Python version
4. Once the connector is installed you are ready to connect your
python program to MySQL.
The following steps to follow while connecting your python
program with MySQL
 Open python
 Import the package required (import mysql.connector)
 Open the connection to database
 Create a cursor instance
 Execute the query and store it in result-set
 Extract data from result-set
 Clean up the environment

5. Importing mysql.connector
import mysql.connector
Or
import mysql.connector as ms
Here “ms” is an alias, so every time we can use “ms” in place of
“mysql.connector”
6. Open a connection to MySQL Database
 To create connection, connect() function is used
 Its syntax is:
o ¤ connect(host=<server_name>,user=<user_name>,
o passwd=<password>[,database=<database>])
 Here server_name means database servername, generally it is
given as “localhost”
 User_name means user by which we connect with
mysql generally it is given as “root”
 Password is the password of user “root”
 Database is the name of database whose data(table) we want to
use
7. Creating Cursor
It is a useful control structure of database connectivity.
When we fire a query to database, it is executed and result-set
(set of records) is sent over he connection in one go.
We may want to access data one row at a time, but query
processing cannot happens as one row at a time, so cursor
help us in performing this task. Cursor stores all the data as a
temporary container of returned data and we can fetch data
one row at a time from Cursor.
8. Creating Cursor and Executing
Query TO CREATE CURSOR
Cursor_name = connectionObject.cursor()
For e.g:
mycursor = mycon.cursor()
TO EXECUTE QUERY
We use execute() function to send query to
connection Cursor_name.execute(query)
For e.g:
mycursor.execute(‘select * from emp’)
Requirements

Hardware Required
· Printer, to print the required documents of the project
· Compact Drive
· Processor : Intel core duo
· Ram : 64 MB
· Hard disk: 20 Gb.

Software Required
· Operating system : Windows 10
· IDLE Python 3.7
· MYSQL Server 8.0
· MYSQL Python Connector 8.0
ABOUT THE PROJECT

“Electronic Shop Management System” is a software that is


used to manage all store product’s information as records in a
simple and automated fashion. This software is based on
MySQL and Python and it is built to eliminate and, in some
cases, reduce the hardships faced by the existing system. The
“Electronic Shop Management System” is a comprehensive
software application that helps store owners manage their
electronic shop. It provides various features and functions that
allow the owner to keep track of customers, employees, and
products. Some of the main features of the system include:

 Main menu: The main menu of the system allows the user to choose
between the options of "Admin", "Customer", "Product Info", and "Exit".
The main menu serves as the starting point for accessing the different
features of the system.

 Admin portal: The "Admin" option leads to the employee portal,


which has options for:

◦ Signing in: Employees can sign in to the system by


entering their employee code and password. After signing in,
employees can access various features of the system such as:

▪ Adding new products: Employees can add new


products to the store's inventory by entering the product details
such as name, description, price, and category.
▪ Modifying existing products: Employees can modify
the amount of stock of any existing product.

◦ Creating an account: Employees can create an account by


entering their employee code, name, password, and other personal
information.

The employee code must be a unique 4-digit number, and the password
must be at least 8 digits long.

◦ Deleting an account: Employees can delete their account by


entering their employee code and password. This feature can be used to
remove the accounts of employees who are no longer working at the
store.

 Customer portal: The "Customer" option leads to the customer


portal, which has options for:

◦ Signing in: Customers can sign in to the system by entering


their user code, name, and password. After signing in, customers can
access various features of the system such as:

• Making purchases: Customers can browse the store's


inventory They can then proceed to checkout, where they can review
their order and confirm their purchase.

◦ Creating an account: Customers can create an account by


entering their user code, name, city, phone number, and password. The
user code must be a unique 4-digit number, and the password must be at
least 8 digits long.

◦ Deleting an account: Customers can delete their account by


entering their user code and password. This feature can be used to
remove the accounts of customers who no longer wish to use the system.

◦ Product information: The "Product Info" option allows the


user to view information about the products in the store. This
information includes the product name, price, and the number of units in
stock. Customers can also search for specific products by name.

 Exit: The "Exit" option allows the user to exit the system.

In addition to these features, the “Electronic Shop Management System”


also includes security measures such as password protection and
encrypted data storage to ensure the confidentiality and integrity of the
store's information. It also provides a user-friendly interface that makes it
easy for store owners and employees to navigate and use the system.
SOURCE CODE

CODES FOR CREATING DATABASE AND TABLES

Creating database named electronicshopms:

Creating tables named employee, electronic_products and users:

Table structures:-
SOURCE CODE FOR CONNECTING MySQL WITH PYTHON

import mysql.connector as sql


conn=sql.connect(host='localhost',user='root',passwd='DavidThomas2006',
database='electronicshopms')
cur=conn.cursor()
conn.commit()
def elecshop():
print("-"*63)
print("============ DSS Electronic Shop Management System
============")
print("-"*63)
ch=int(input("""1.Admin
2.Customer
3.Product Info
4.Exit
Enter a Choice: \n"""))
print("-"*50)
if ch==1:
print("\n")
employee()
elif ch==2:
print("\n")
users()
elif ch==3:
print("\n")
stock1()
elif ch==4:
print("Thank You!")
else:
print("Invalid Choice")
def employee():
print("-"*37)
print("========== Employee Portal ==========")
print("-"*37)
choice=int(input("""1.SIGN IN
2.CREATE ACCOUNT
3.DELETE ACCOUNT
4.Back to Main Menu
Enter a Choice: \n"""))
print("-"*50)
if choice==1:
print("\n")
emp_log()
elif choice==2:
print("\n")
emp_si()
elif choice==3:
print("\n")
emp_del()
elif choice==4:
print("\n")
elecshop()
else:
print("Invalid Choice")
elecshop()
def emp_log():
print("\n")
print("-"*38)
print("========== EMPLOYEE SIGN IN ==========")
print("-"*38)
f=[]
code=int(input("Enter your Employee Code Number:"))
name=input("Enter you Name:")
paas=int(input("Enter your Password:"))
cur.execute("select * from employee where ecode={} and
password={}".format(code,paas))
dat=cur.fetchall()
hi=list(dat)
if hi==f:
print("PASSWORD & OR EMPLOYEE CODE IS INVALID")
print("")
wro=int(input("""1.Try Again
2.Back to Main Menu
3.Exit
Enter a Choice: \n"""))
if wro==1:
emp_log()
elif wro==2:
elecshop()
elif wro==3:
print("Thank You!")
else:
print("Invalid Choice")
elecshop()
else:
print("\n Welcome",name,"!,Have a nice day...... \n")
emp_pri()
def emp_si():
fd=[]
print("-"*51)
print("========== EMPLOYEE ACCOUNT REGISTRATION ==========")
print("-"*51)
we=input("Enter Password:")
if we=='password':
cd=int(input("Enter an Employee Code(4 digits):"))
cur.execute("select * from employee where ecode="+str(cd))
hat=cur.fetchall()
h3=list(hat)
if h3!=fd:
print("EMPLOYEE CODE ALREADY EXISTS")
print("")
choice1=int(input('''1.Back to Main Menu
2.Back to Admin
3.Try Again
4.Exit
Enter a Choice: \n'''))
if choice1==1:
elecshop()
elif choice1==2:
employee()
elif choice1==3:
emp_si()
elif choice1==4:
print("Thank You!")
else:
print("Invalid Choice")
elecshop()
else:
r=input("Enter your Name:")
pre=int(input("Enter a Password(8 digits):"))
ps4=int(input("Reenter your Password:"))
if pre==ps4:
cur.execute("insert into employee values({},'{}',
{})".format(cd,r,pre))
conn.commit()
print("YOUR EMPLOYEE ACCOUNT HAS BEEN CREATED
SUCCESSFULLY")
print("")
emp_pri()
else:
print("Passwords do not match")
print("")
cho1=int(input('''1.Back to Main Menu
2.Back to Admin
3.Try Again
4.Exit
Enter a Choice: \n'''))
if cho1==1:
elecshop()
elif cho1==2:
employee()
elif cho1==3:
emp_si()
elif cho1==4:
print("Thank You!")
else:
print("Invalid Choice")
elecshop()
else:
print("Incorrect Password")
employee()
def emp_del():
print("-"*47)
print("========== EMPLOYEE ACCOUNT DELETION ==========")
print("-"*47)
x=[]
da=int(input("Enter the Employee Code to be deleted:"))
cur.execute("select ecode,ename from employee where ecode="+str(da))
data2=cur.fetchall()
if data2==x:
print("")
print("EMPLOYEE CODE DOES NOT EXIST")
print("")
employee()
else:
for row in data2:
print(" Employee Details ")
print(" EMPLOYEE_CODE:",row[0])
print(" EMPLOYEE_NAME:",row[1])
conn.commit()
print("")
chi8=int(input("""Are you sure you want to delete your account?
1.Yes
2.No

Enter your choice: """))


if chi8==1:
ert=[]
pase=int(input("Enter your Password:"))
cur.execute("select * from employee where ecode={} and
password={}".format(da,pase))
dat=cur.fetchall()
his=list(dat)
if his==ert:
print("PASSWORD & OR EMPLOYEE CODE IS INVALID")
print("")
employee()
else:
cur.execute("delete from employee where ecode={}".format(da))
print("YOUR ACCOUNT HAS BEEN DELETED SUCCESSFULLY")
print("")
print("Thank you for being with us!")
print("")
conn.commit()
elecshop()
if chi8==2:
print("")
employee()

def update():
print("Updating Stock")
p='password'
cp=input("Enter the password:")
if cp==p:
stock()
a=int(input("Enter the Product Number : "))
b=int(input("Enter how much stock should be added:"))
cur.execute("update electronic_products set Stock = Stock + "+str( b ) +
" where Pno=" +str(a))
conn.commit()
cur.execute("select Pname,Pno,Stock from electronic_products where
Pno="+str(a))
dat=cur.fetchall()
for row in dat:
print("Available Stock Details ")
print("Product Name:",row[0])
print("Product Number:",row[1])
print("Stock:",row[2])
print("Updated Succesfully")
print("")
emp_pri()
else:
print ("Password is incorrect")
emp_pri()
def add():
dp='password'
da=input("Enter the Password:")
if dp==da:
print("New Product")
print('')
fi=int(input("Enter the new product number(6 digits):"))
fe=input("Enter the new product name:")
st=int(input("Enter the stock to be added:"))
price=int(input("Enter the price of the product:"))
cur.execute("Insert into electronic_products values('{}',
{},'{}','{}')".format(fe,fi,st,price))
print("Updated Successfully!")
conn.commit()
print("")
emp_pri()
else:
print("Password is incorrect")
emp_pri()
def emp_pri():
print("-"*41)
print("========== Employee Privileges ==========")
print("-"*41)
c3=int(input("""1.Add Products
2.Update Stock
3.Back to Main Menu
Enter a choice: \n"""))
print("-"*50)
if c3==1:
print("\n")
add()
elif c3==2:
print("\n")
update()
elif c3==3:
print("\n")
elecshop()
else:
print("Invalid Choice")
elecshop()
def users():
print("-"*37)
print("========== Customer Portal ==========")
print("-"*37)
c4=int(input("""1.SIGN IN
2.CREATE ACCOUNT
3.DELETE ACCOUNT
4.Back to Main Menu
Enter a choice: \n"""))
print("-"*50)
if c4==1:
print("\n")
users_log()
elif c4==2:
print("\n")
users_si()
elif c4==3:
print("\n")
users_del()
elif c4==4:
print("\n")
elecshop()
else:
print("Invalid Choice")
elecshop()
def users_log():
print("-"*38)
print("========== CUSTOMER SIGN IN ==========")
print("-"*38)
k=[]
cod=int(input("Enter your User Code:"))
name=input("Enter your Name:")
p1=int(input("Enter your Password:"))
cur.execute("select * from users where ucode = {} and password =
{}".format(cod , p1))
dat1=cur.fetchall()
hi1=list(dat1)
if hi1==k:
print("PASSWORD & OR USERCODE IS INVALID")
print("")
wro=int(input("""1.Try Again
2.Back to Main Menu
3.Exit \n
Enter your choice: """))
if wro==1:
users_log()
elif wro==2:
elecshop()
elif wro==3:
print("Thank You!")
else:
print("Invalid Choice")
elecshop()
else:
print("")
print("Welcome",name,"!")
print("")
users_pri()
def users_pri():
print("-"*41)
print("========== Customer Privileges ==========")
print("-"*41)
c5=int(input("""1.View Product Information
2.Purchase
3.Back to Main Menu
Enter a choice: \n"""))
print("-"*50)
if c5==1:
print("\n")
stock()
users_pri()
elif c5==2:
print("\n")
purchase()
elif c5==3:
print("\n")
elecshop()
else:
print("Invalid Choice")
elecshop()
def users_si():
x=[]
print("-"*49)
print("========== CUSTOMER ACCOUNT REGISTRATION ==========")
print("-"*49)
u=int(input("Enter a User Code(in 4 digits):"))
cur.execute("select * from users where ucode="+str(u))
hat=cur.fetchall()
h2=list(hat)
if h2!=x:
print("")
print("USER CODE ALREADY EXITS")
print("")
c6=int(input('''1.Back to Main Menu
2.Back to Customer Portal
3.Try Again
4.Exit
Enter your choice: \n'''))
if c6==1:
elecshop()
elif c6==2:
users()
elif c6==3:
users_si()
elif c6==4:
print("Thank You!")
else:
print("Invalid Choice")
elecshop()
else:
n=input("Enter your Name:")
c=input("Enter your City:")
while True:
z=input("Enter your Phone Number (9 digits):")
if len(z) == 9 and z.isdigit():
break
else:
print("Phone number must be 9 digits. Please try again.")
pse=int(input("Enter a Password(upto 8 digits):"))
ps2=int(input("Reenter the Password:"))
if pse==ps2:
cur.execute("insert into users values({},'{}',{},'{}',
{})".format(u,n,pse,c,z))
conn.commit()
print("USER ACCOUNT HAS BEEN CREATED SUCCESSFULLY!")
print("")
users_pri()
else:
print("Passwords do not match")
print("")
cho2=int(input('''1.Back to Main Menu
2.Back to Customer Portal
3.Try Again
4.Exit
Enter your choice: \n'''))
if cho2==1:
elecshop()
elif cho2==2:
users()
elif cho2==3:
emp_si()
elif cho2==4:
print("Thank You!")
else:
print("Invalid Choice")
elecshop()

def users_del():
print("-"*47)
print("========== CUSTOMER ACCOUNT DELETION ==========")
print("-"*47)
y=[]
de=int(input("Enter the User Code to be Deleted:"))
cur.execute("select ucode,uname,city,phone_no from users where
ucode="+str(de))
data=cur.fetchall()
if data==y:
print("")
print("USER ACCOUNT DOES NOT EXIST")
print("")
users()
else:
for row in data:
print(" User Details ")
print(" User Code:",row[0])
print(" User Name:",row[1])
print(" City:",row[2])
print(" Phone no:",row[3])
conn.commit()
print("")
chi8=int(input("""Are you sure you would like to delete this account?
1.Yes
2.No \n"""))
if chi8==1:
fh=[]
paes=int(input("Enter your Password:"))
cur.execute("select * from users where ucode={} and
password={}".format(de,paes))
dat=cur.fetchall()
hi=list(dat)
if hi==fh:
print("PASSWORD & OR USER CODE IS INVALID")
print("")
employee()
else:
cur.execute("delete from users where ucode={}".format(de))
print("YOUR ACCOUNT HAS BEEN DELETED SUCCESSFULLY!")
print("")
print("Thank you for being with us!")
print("")
conn.commit()
elecshop()
def stock1():
print("\n")
print("-"*80)
print(" "*37,"STOCK")
print("-"*85)
cur.execute("select * from electronic_products")
data=cur.fetchall()
print(f"|{'Product Name'.center(35)}|{'Product Number'.center(18)}|
{'Stock'.center(13)}|{'Price'.center(13)} | ")
for i in data:
print("|%-35s|%-18s|%-13s|%-14s|"%i)
print("-"*85)
elecshop()

def purchase():
print("-"*40)
print("========== Purchasing Section ==========")
print("-"*40)
stock()
nm=input("Enter the Product Name:")
print("")
cur.execute("select * from electronic_products where
Pname='{}'".format(nm))
dat1=cur.fetchall()
hi1=list(dat1)
if hi1==[]:
print("This Product does not Exist")
print("")
c7=int(input('''1.Try Again
2.Back to Customer Priveleges
3.Exit
Enter your choice: \n'''))
if c7==1:
purchase()
elif c7==2:
users_pri()
elif c7==3:
print("Thank You!")
else:
print("Invalid Choice")
users_pri()
else:
cur.execute("select Pname,Stock,Price from electronic_products where
Pname='{}'".format(nm))
data=cur.fetchall()
for row in data:
print('')
print("Available Stock Details:")
print("")
print("-Product Name:",row[0])
print("-Stock:",row[1])
print("-Price of the product in AED:",row[2])
conn.commit()
print('')
ch=int(input("""Would you like to purchase this item?
1.Yes
2.No \n"""))
if ch==1:
amo=int(input("Enter the quantity="))
# Add check to make sure the user cannot purchase more items
than the available stock
if amo > int(row[1]):
print("You cannot purchase more items than the available
stock")
print("Please try again")
purchase()
else:
rec=int(row[2])*amo
print("")
print("The Final Amount in AED=",rec)
print('')
ch1=int(input("""Do you want to continue with your purchase?
1.Yes
2.No \n"""))
print('')
print("="*80)
print('')
if ch1==1:
cur.execute("update electronic_products set Stock=Stock-{}
where Pname='{}'".format(amo,nm))
print("\n========== RECEIPT ==========\n")
for row in hi1:
print("Product Number:",row[1])
print("Product Name:",row[0])
print("Quantity:",amo)
print("Price:",row[3])
row_total = int(row[3])*amo
print("Total:", row_total)
print('-'*29)
conn.commit()
print("")
print("Would you like to continue purchasing?")
ch2=int(input("""1.Yes
2.No
Enter your Choice: \n"""))
if ch2==1:
purchase()
elif ch2==2:
print("Thank you for your Patronage")
print("="*80)
users_pri()
else:
print("Invalid Choice")
print("="*80)
users_pri()
elif ch1==2:
print("Thank You")
print("="*80)
users_pri()
else:
print("ERROR 404 : DETECTED")
users_pri()
elif ch==2:
print("Thank You")
print("="*80)
users_pri()
else:
print("Invalid Choice")
print("="*80)
users_pri()

def stock():
print("\n")
print("-"*80)
print(" "*37,"STOCK")
print("-"*85)
cur.execute("select * from electronic_products")
data=cur.fetchall()
print(f"|{'Product Name'.center(35)}|{'Product Number'.center(18)}|
{'Stock'.center(13)}|{'Price'.center(13)} | ")
for i in data:
print("|%-35s|%-18s|%-13s|%-14s|"%i)
print("-"*85)
elecshop()
SAMPLE RUN
SUGGESTIONS FOR IMPROVEMENT
This program could be made more user friendly by adding new functions that
allowed the employee to delete unnecessary products and allow them to
modify any detail of the product, while also adding new features for
customers that allow them to buy multiple items at once and allowing them
to view their previous purchases.

The program could also have different passwords for different employee jobs
allowing those with appropriate jobs to access them and making it more
secure.
BIBLIOGRAPHY

l Computer Science with Python –Sumita Arora


l www.python.org
l www.dev.mysql.com
l www.google.com
l www.wikipedia.org
l https://www.w3schools.com/python/python_mysql_getstarted.asp

You might also like