Project Report
Project Report
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
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
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.
The employee code must be a unique 4-digit number, and the password
must be at least 8 digits long.
Exit: The "Exit" option allows the user to exit the system.
Table structures:-
SOURCE CODE FOR CONNECTING MySQL WITH PYTHON
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