程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python operating Mysql to make a supermarket management system

編輯:Python

introduction :

        The project makes two ports , Administrator side and customer side , The administrator realizes the operation of accessing, adding, deleting, modifying and querying the data tables in the database , Data can be stored for a long time , And show it , It is convenient for supermarket administrators to manage supermarket commodities . The client can access the database , And make a shopping cart pattern , And settle the goods selected by customers , It is convenient for customers to choose products , There is no long-term storage of customers' shopping data ( I don't want to do it ).

        Besides , This is also a relatively complete project , I've been cooking for a while for this liver , Articles are hard won , Kind people, please pay attention to , Support this blogger ! thank ! mua .

1. Import pymysql modular  

Import... From the command prompt : Input cmd Get into , Then input

pip install pymysql 

2. stay python Internal connection mysql, And create a data table    test1.py

 2.1 Connect to database

import pymysql
# Connect to database
conn = pymysql.connect(
host='localhost',
user='root',
password='123abc',
charset='utf8'
)
# Get cursor
cursor = conn.cursor()

2.2 Create data table , And input data

# Create database
db_student = "create database if not exists dbtest"
cursor.execute(db_student)
# Create a fruit table
sql_use = 'use dbtest'
cursor.execute(sql_use)
sql_table = 'create table if not exists fruits (stuID int primary key, ' \
'stuName varchar(20), stuPrice int)'
cursor.execute(sql_table)
# insert data
sql_one = "insert into fruits (stuID, stuName, stuPrice) values (%d, '%s', %d)"
data1 = (1001, ' Banana ', 20)
data2 = (1002, ' Apple ', 21)
data3 = (1003, ' Cherry ', 20)
data4 = (1004, ' Pineapple ', 19)
data5 = (1005, ' citrus ', 22)
for i in [data1, data2, data3,data4, data5]:
cursor.execute(sql_one % i)
conn.commit()

 2.3 Open the database graphical page tool , If there is such a table, it indicates that the creation is successful ( The sixth data is added by the running code ), You can also use the command prompt to find .

  3. Design supermarket management server code    test2.py

   3.0  Connect to database

import pymysql
# Database connection
def connect():
conn = pymysql.connect(host='localhost',
port=3306,
user='root',
password='123abc',
database='dbtest', # Select database
charset='utf8')
# Get operation cursor
cursor = conn.cursor()
return {"conn": conn, "cursor": cursor}

   3.1 Supermarket administrator operation terminal , Realization effect : It can add, delete, check and modify the data in the database table , And keep it for a long time .

        3.1.1 Insert the product

# Administrator operation , Insert product
def add_goods():
# Get operation cursor
connection = connect()
conn, cursor = connection['conn'], connection['cursor']
stuID = int(input(' Please enter the item number to insert :'))
stuName = input(' Please enter the name of the product to be inserted :')
stuPrice = input(' Please enter the product price to insert :')
add = cursor.execute('insert into fruits (stuID, stuName , stuPrice)\
values(%s,%s,%s)',(stuID, stuName ,stuPrice))
if add == 1: # Use the cursor to find the data table , If there is this table capture in the database , No exception was reported
conn.commit() # Transfer data into the database
print(' Insert the success !')
else:
print(' Insert the failure !')
show_commend() # return show_commend() class 

        3.1.2 Take the goods off the shelf ( Delete )

# Delete product record
def delete_goods():
# Get operation cursor
connection = connect()
conn, cursor = connection['conn'], connection['cursor']
stuID= int(input(' Enter the number of the item you want to delete :'))
delete = cursor.execute('delete from fruits where stuID= {}' .format(stuID))
if delete == 1: # Use the cursor to find the data table , If there is this table capture in the database , No exception was reported
conn.commit() # Transfer data into the database
print(' Delete successful !')
else:
print(' Delete failed !')
show_commend() # return show_commend() class

          3.1.3 Perform a single search operation on the item ( How to find the trade name , How to find the item number )


# Administrator operation , To query a single commodity, query by commodity number
def g_by_id():
# Get operation cursor
connection = connect()
conn, cursor = connection['conn'], connection['cursor']
choice_id = int(input(' Please enter the item number :'))
cursor.execute('select * from fruits where stuID=%s',(choice_id))
fruits = cursor.fetchall() # Use the cursor to find the data table , If there is this table capture in the database , No exception was reported
for j in fruits:
print("==============================================")
print('--- Product id :{} Name of commodity :{} commodity price :{}---' .format(j[0], j[1], j[2]))
print(' The query is successful ')
print("==============================================")
# The design continues to execute the next operation code
re = input(' Continue to query (yes/no):')
if re == 'yes': # perform yes return g_by_name,no Return to the operation page
g_by_id()
else:
show_commend() # return show_commend() class
# Administrator operation , Query a single product by product name ( In case the item number is entered incorrectly )
def g_by_name():
# Get operation cursor
connection = connect()
conn, cursor = connection['conn'], connection['cursor']
choose_name = input(' Please enter the product name :')
cursor.execute('select * from stu where name =%s',(choose_name))
students = cursor.fetchall() # Use the cursor to find the data table , If there is this table capture in the database , No exception was reported
for j in students:
print("==============================================")
print('--- Product id :{} Name of commodity :{} commodity price :{}---'.format(j[0], j[1], j[2]))
print(' The query is successful ')
print("==============================================")
re = input(' Continue to query yes/no:')
if re == 'yes': # perform yes return g_by_name,no Return to the operation page
g_by_name()
else:
show_commend() # return show_commend() class 

        3.1.4 Modify the goods ( Change the number , name , Price )

# Administrator operation , Modify the goods
def update_goods():
# Get operation cursor
connection = connect()
conn, cursor = connection['conn'], connection['cursor']
cur = int(input(' Please enter the item number you want to modify :'))
cursor.execute('select * from fruits where stuID = %s', (cur))
if cursor.fetchall() == []: # Use the cursor to find the data table , If there is this table capture in the database , No exception was reported
print(' The item number was not found {}'.format(cur))
# The design continues to execute the next operation code
mc3 = input(' Whether to query again ?(yes/no)')
if mc3 != 'no': # perform yes return g_by_name,no Return to the operation page
update_goods()
else:
show_commend() # return show_commend() class
else:
print('==============')
print('1、 Change item number ')
print('2、 Change the product name ')
print('3、 Modify the price of goods ')
print('==============')
mc2 = int(input(' Please enter the corresponding operation number :'))
if mc2 == 1:
stuID= input(' Please enter the revised item number :')
a = cursor.execute('update fruits set stuID = %s where stuID= %s', (stuID, cur))
if a == 1: # Use the cursor to find the data table , If there is this table capture in the database , No exception was reported
conn.commit() # Transfer data into the database
print(' Modification successful !')
else:
print(' Modification failed !')
elif mc2 == 2:
stuName = input(' Please enter the modified product name :')
a = cursor.execute('update fruits set stuName = %s where stuID = %s', (stuName, cur))
if a >= 1: # Use the cursor to find the data table , If there is this table capture in the database , No exception was reported
conn.commit() # Transfer data into the database
print(' Modification successful !')
else:
print(' Modification failed !')
elif mc2 == 3:
stuPrice = int(input(' Please enter the revised commodity price :'))
a = cursor.execute('update fruits set stuPrice= %s where stuID = %s', (stuPrice, cur))
if a >= 1: # Use the cursor to find the data table , If there is this table capture in the database , No exception was reported
conn.commit() # Transfer data into the database
print(' Modification successful !')
else:
print(' Modification failed !')
else:
pass # Occupy an empty space
show_commend() # return show_commend() class 

        3.1.5 Check all the products in the supermarket

# Administrator operation , Query all product information
def goods_all():
# Get operation cursor
connection = connect()
conn, cursor = connection['conn'], connection['cursor']
cursor.execute('select * from fruits')
fruits = cursor.fetchall() # Use the cursor to find the data table , If there is this table capture in the database
print("=============================================")
print(" The commodity list is :")
print("=============================================")
for j in fruits:
print('--- Product id :{}--- Name of commodity :{}--- commodity price :{}---' .format(j[0], j[1], j[2]))
print("=============================================")
show_commend()

        3.1.5  Create a class to exit the operation side of the administrator page

# Exit the administrator commodity management system
def end_goods():
print(" It has been proposed that !")
exit()

        3.1.6  Selector for a single query product method

goods_dict1={'a':g_by_name,'b':g_by_id}
# Administrator operation , Select a method to query a single item
def show_querycondition():
cmd=input(" Please input the operation instruction : Enter the product name to query (a) Enter the item number to query (b)\n")
if cmd not in goods_dict1:
print(' Input error !')
else:
goods_dict1[cmd]() # Get into cmd Corresponding values In the output class 

       3.1.7  The supermarket administrator selects the operation type class

goods_dict2={'a':goods_all,'b':update_goods,'c':add_goods,'d':show_querycondition,'e':delete_goods,'i':end_goods}
# The staff of shopping malls add, delete, check and modify commodities
def show_commend():
cmd=input(" Please input the operation instruction : Check all items (a) Modify the goods (b) Insert product (c) Query a single item (d) Delete item (e) sign out (i)\n")
if cmd not in goods_dict2:
print(' Input error !')
Start()
else:
goods_dict2[cmd]() # Get into cmd Corresponding values In the output class

3.2 Customer user operation end , Realization effect : Shopping cart mode , Select the category and quantity of the goods , Settlement , No long-term preservation .

        3.2.1 Transfer out the tables of the database and convert them to the specified list form

def select_sql():
# Get operation cursor
connection = connect()
conn, cursor = connection['conn'], connection['cursor']
sql = "select * from fruits"
try: # Use the cursor to find the data table , If there is this table capture in the database , No exception was reported
cursor.execute(sql)
results = cursor.fetchall()
results=list(results)
return results
except Exception as e: # Capture exception
raise e
finally:
cursor.close()
conn.close()
data=select_sql() # Get selct_sql Tuple object
goods=[] # Use the empty list to transfer the data
# By traversing selct_sql Tuple objects are converted into dictionaries , Then turn it into a list and add it to goods In the list
for i in data:
var = {'barcode': i[0], 'product': i[1], 'price': i[2]} # Get data and turn it into a dictionary
li=[var]
goods.extend(li) # Add data to goods In the list
goods_list=[] # Use the empty list to transfer the data

        3.2.2 Supermarket customer side home page

# Show customers the information about the goods in the store ( Go to the home page of the store )
def show_list():
print(' Serial number --------- Bar code --------- Name of commodity --------- The unit price --------- Number --------- Subtotal ')
for j in range(len(goods_list)):
print("{0:<12}{1:<15}{2:<14}{3:<12}{4:<12}{5:<12}".
format(j, goods_list[j].get('barcode'), goods_list[j].get('product'),
goods_list[j].get('price'), goods_list[j].get('number_add'), goods_list[j].
get('sum_add')))

        3.2.3  Add items to cart

# Customer operation , Add items to cart
def add():
barcode_add=int(input(" Please enter the barcode of the item to be added :"))
for i in goods:
if barcode_add==i['barcode']:
goods_list.append(i)
numbers_add=int(input(" Please enter the quantity of goods to be purchased "))
sum_add=numbers_add*i.get('price')
i['number_add']=numbers_add
i['sum_add']=sum_add
show_list() # return show_list class 

        3.2.4 Modify the items in the shopping cart

# Customer operation , Modify the product information in the shopping cart
def edit():
barcode_edit= int(input(" Please enter the barcode of the product to be modified :"))
numbers_edit=int(input(" Please enter the quantity of the item to be modified "))
for i in goods_list:
if barcode_edit==i['barcode']:
i['sum_add']=numbers_edit*i.get('price')
i['number_add']=numbers_edit
show_list() # return show_list class 

        3.2.5 Delete items from cart


# Customer operation , Delete items from cart
def delete():
barcode_delete = int(input(" Please enter the barcode of the product to be modified :"))
for i in goods_list:
if barcode_delete==i['barcode']:
goods_list.remove(i)
show_list() # return show_list class

        3.2.6 Settle the items in the shopping cart

# Customer operation , Settlement goods
def payment():
print('-'*100)
show_list()
print('-'*100)
sum=0
for i in goods_list:
sum=sum+i['sum_add']
print(" Total price for :",sum)
print(" Please scan !")
print(" looking forward to your next visit ")
exit()

        3.2.7 Make customers browse supermarket commodities

# Customer operation , Click to browse the product information
def show_goods():
print(" bar code ------------ Name of commodity ------------ The unit price ")
for i in range(len(goods)):
print("{0:<15}{1:<17}{2:<}".format(goods[i].get('barcode'),goods[i].get('product'),goods[i].get('price')))
print('-'*100)

        3.2.8 Make customer command operation class

cmd_dict={'a':add,'e':edit,'d':delete,'p':payment,'s':show_goods}
# Customer operation instructions
def shopping_commend():
cmd=input(" Please input the operation instruction : add to (a) modify (e) Delete (d) Settlement (p) Supermarket goods (s)\n")
if cmd not in cmd_dict:
print(' Input error !')
else:
cmd_dict[cmd]() # Get into cmd Corresponding values In the output class 

3.3 Login ( Start page login ( Administrator login , Client login )) 

        3.3.1 Administrator Login Class

# Store administrator login
def Administrator():
print("=========================================")
print(" Administrator login page :")
print("=========================================")
root = ['aaa', 'bbb', 'ccc', 'ddd', 'fff']
root_password = ['123', '456', '789', '223', '245']
a = list(zip(root, root_password)) # Convert to a one-to-one list
num = 0 # Define a beginning as 0 Count variables for
while True:
list_1 = input(" Please enter the administrator's name :")
list_1=''.join(list_1.split()) # Remove the blank space from the input , Ensure that no error will be reported due to extra space in the name or password string
l = list_1.split(",") # String to list
list_2 = input(" Please input a password :") # Remove the blank space from the input , Ensure that no error will be reported due to extra space in the name or password string
list_2=''.join(list_2.split())
k = list_2.split(",")
t = list(zip(l, k)) # Convert to a one-to-one list
c = [] # Define an empty list
for i in range(len(t)):
c.append(0)
for i in range(len(a)): # Yes a List for traversal , If a The string in the list has an equal to t list , Join in c in
for j in range(len(t)):
if a[i] == t[j]:
c[j] = c[j] + 1
text1 = ''.join(str(i) for i in c) # because join Inside is the string type , Let traversal and type conversion proceed synchronously
text1 = int(text1) # hold text1 Convert type to integer *( Not 0 And 1)
if text1 == 1:
print(" Landing successful !")
while True:
show_commend()
else:
num += 1
if num < 3:
print(" Wrong user name or password , Please re-enter :")
if num >= 3:
print(" The user name or password has been wrong 3 Time , Please try again later !")
break

        3.3.2 Client login class

# Customer login
def Client():
name= ['aaa', 'bbb', 'ccc', 'ddd', 'fff']
name_password = ['123', '456', '789', '223', '245']
a = list(zip(name, name_password)) # Convert to a one-to-one list
num = 0 # Define a beginning as 0 Count variables for
print("=========================================")
print(" Customer login page :")
print("=========================================")
while True:
list_1 = input(" Your name, please :")
list_1=''.join(list_1.split()) # Remove the blank space from the input , Ensure that no error will be reported due to extra space in the name or password string
l = list_1.split(",") # String to list
list_2 = input(" Please input a password :")
list_2=''.join(list_2.split()) # Remove the blank space from the input , Ensure that no error will be reported due to extra space in the name or password string
k = list_2.split(",")
t = list(zip(l, k)) # Convert to a one-to-one list
c = [] # Define an empty list
for i in range(len(t)):
c.append(0)
for i in range(len(a)): # Yes a List for traversal , If a The string in the list has an equal to t list , Join in c in
for j in range(len(t)):
if a[i] == t[j]:
c[j] = c[j] + 1
text1 = ''.join(str(i) for i in c) # because join Inside is the string type , Let traversal and type conversion proceed synchronously
text1 = int(text1) # hold text1 Convert type to integer *( Not 0 And 1)
if text1 == 1:
print(" Landing successful !")
print(" Welcome to my supermarket ")
print(" Here is a list of my products , Please choose :")
show_goods()
print(" Have not purchased goods yet ")
while True:
shopping_commend()
else:
num += 1
if num < 3:
print(" Wrong user name or password , Please re-enter :")
if num >= 3:
print(" The user name or password has been wrong 3 Time , Please try again later !")
break

        3.3.3 Start page Login Class , start-up !

# The starting page
def Start():
print("=========================================")
print(" Welcome to XXX Shopping mall electronic system !")
print("=========================================")
use=int(input(" For customer login, please press 1, To log in as a store administrator, please press 2:"))
if use==1:
Client()
else:
Administrator()
Start() # perform Start class 

3. Realization effect ( Here's the picture )

 

 

 

 

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved