欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python操作mysql實現(xiàn)一個超市管理系統(tǒng)

 更新時間:2022年12月22日 11:09:18   作者:Huang?st  
超市管理系統(tǒng)有管理員和普通用戶兩條分支,只需掌握Python基礎(chǔ)語法,就可以完成這個項目,下面這篇文章主要給大家介紹了關(guān)于python操作mysql實現(xiàn)一個超市管理系統(tǒng)的相關(guān)資料,需要的朋友可以參考下

前言

該項目制作了兩個端口,管理員端和顧客用戶端,管理員端實現(xiàn)了對數(shù)據(jù)庫中的數(shù)據(jù)表進行訪問和增刪改查操作,數(shù)據(jù)可長期保存,并展示出來,方便超市管理員對超市商品的管理。顧客端實現(xiàn)了對數(shù)據(jù)庫進行訪問,并制作一個購物車模式,并對顧客選擇的商品進行結(jié)算,方便顧客選擇商品,沒有制作對顧客的購物數(shù)據(jù)進行長期保存(不想做了)。

此外,這也是一個相對比較完整的項目了呢,菜菜的我可是為了這個肝了不久呢,文章來之不易,好心人請你點贊關(guān)注一下,支持一下本博主吧!感謝!么么噠。

1.導入pymysql 模塊 

通過命令提示符導入:輸入cmd 進入,然后輸入

pip install pymysql 

2.在python里連接mysql,并創(chuàng)建數(shù)據(jù)表   test1.py  

2.1 連接數(shù)據(jù)庫

import pymysql
# 連接數(shù)據(jù)庫
conn = pymysql.connect(
    host='localhost',
    user='root',
    password='123abc',
    charset='utf8'
)
# 獲得游標
cursor = conn.cursor()

2.2 創(chuàng)建數(shù)據(jù)表,并輸入數(shù)據(jù)

# 創(chuàng)建數(shù)據(jù)庫
db_student = "create database if not exists dbtest"
cursor.execute(db_student)
# 創(chuàng)建水果表
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)
# 插入數(shù)據(jù)
sql_one = "insert into fruits  (stuID, stuName, stuPrice) values (%d, '%s', %d)"
data1 = (1001, '香蕉',  20)
data2 = (1002, '蘋果',  21)
data3 = (1003, '櫻桃',  20)
data4 = (1004, '鳳梨',  19)
data5 = (1005, '柑橘',  22)
for i in [data1, data2, data3,data4, data5]:
    cursor.execute(sql_one % i)
conn.commit()

 2.3 打開數(shù)據(jù)庫圖形化頁面工具,如有該表則說明創(chuàng)建成功(第六條數(shù)據(jù)是后面運行代碼加上去的),也可以用命令提示符查找。

3.設(shè)計超市管理服務(wù)端代碼   test2.py    

3.0  連接數(shù)據(jù)庫

import pymysql
# 數(shù)據(jù)庫連接
def connect():
    conn = pymysql.connect(host='localhost',
                           port=3306,
                           user='root',
                           password='123abc',
                           database='dbtest',  #選擇數(shù)據(jù)庫
                           charset='utf8')
    # 獲取操作游標
    cursor = conn.cursor()
    return {"conn": conn, "cursor": cursor}

3.1 超市管理員操作端,實現(xiàn)效果:能對數(shù)據(jù)庫表的數(shù)據(jù)進行增刪查改,并長期保存。

3.1.1 對商品插入操作

#管理員操作,插入商品
def add_goods():
    # 獲取操作游標
    connection = connect()
    conn, cursor = connection['conn'], connection['cursor']
    stuID = int(input('請輸入要插入的商品編號:'))
    stuName = input('請輸入要插入的商品名字:')
    stuPrice = input('請輸入要插入的商品價格:')
    add = cursor.execute('insert into fruits (stuID, stuName , stuPrice)\
                   values(%s,%s,%s)',(stuID, stuName ,stuPrice))
    if add == 1:     #利用游標查找數(shù)據(jù)表,如果數(shù)據(jù)庫中有此表捕獲,沒有報異常
        conn.commit()   #把數(shù)據(jù)傳入數(shù)據(jù)庫
        print('插入成功!')
    else:
        print('插入失?。?)
    show_commend()     #返回show_commend()類

3.1.2 對商品進行下架操作(刪除)

#刪除商品記錄
def delete_goods():
    # 獲取操作游標
    connection = connect()
    conn, cursor = connection['conn'], connection['cursor']
    stuID= int(input('輸入想要刪除商品的編號:'))
    delete = cursor.execute('delete from fruits where stuID= {}' .format(stuID))
    if delete == 1:    #利用游標查找數(shù)據(jù)表,如果數(shù)據(jù)庫中有此表捕獲,沒有報異常
        conn.commit()    #把數(shù)據(jù)傳入數(shù)據(jù)庫
        print('刪除成功!')
    else:
        print('刪除失??!')
    show_commend()  #返回show_commend()類

3.1.3 對商品進行單個查找操作(商品名查找方法,商品編號查找方法)

 
#管理員操作,查詢單個商品之按商品編號查詢
def g_by_id():
    # 獲取操作游標
    connection = connect()
    conn, cursor = connection['conn'], connection['cursor']
    choice_id = int(input('請輸入商品編號:'))
    cursor.execute('select * from fruits where stuID=%s',(choice_id))
    fruits = cursor.fetchall()    #利用游標查找數(shù)據(jù)表,如果數(shù)據(jù)庫中有此表捕獲,沒有報異常
    for j in fruits:
        print("==============================================")
        print('---商品編號:{}    商品名稱:{}    商品價格:{}---' .format(j[0], j[1], j[2]))
        print('查詢成功')
        print("==============================================")
#設(shè)計繼續(xù)執(zhí)行下一步操作代碼
        re = input('是否繼續(xù)查詢(yes/no):')
        if re == 'yes':  # 執(zhí)行yes返回g_by_name,no返回到操作頁面
            g_by_id()
        else:
            show_commend()  # 返回show_commend()類
 
 
#管理員操作,查詢單個商品之按商品名稱查詢(以防商品編號輸入錯誤)
def g_by_name():
    # 獲取操作游標
    connection = connect()
    conn, cursor = connection['conn'], connection['cursor']
    choose_name = input('請輸入商品名稱:')
    cursor.execute('select * from stu where name =%s',(choose_name))
    students = cursor.fetchall()   #利用游標查找數(shù)據(jù)表,如果數(shù)據(jù)庫中有此表捕獲,沒有報異常
    for j in students:
        print("==============================================")
        print('---商品編號:{}    商品名稱:{}    商品價格:{}---'.format(j[0], j[1], j[2]))
        print('查詢成功')
        print("==============================================")
        re = input('是否繼續(xù)查詢yes/no:')
        if re == 'yes':  #執(zhí)行yes返回g_by_name,no返回到操作頁面
            g_by_name()
        else:
            show_commend()  #返回show_commend()類

3.1.4 修改商品(修改編號,名稱,價格)

#管理員操作,修改商品
def update_goods():
    # 獲取操作游標
    connection = connect()
    conn, cursor = connection['conn'], connection['cursor']
    cur = int(input('請輸入想要修改的商品編號:'))
    cursor.execute('select * from fruits where stuID = %s', (cur))
    if cursor.fetchall() == []:       #利用游標查找數(shù)據(jù)表,如果數(shù)據(jù)庫中有此表捕獲,沒有報異常
        print('未查找該商品的編號{}'.format(cur))
# 設(shè)計繼續(xù)執(zhí)行下一步操作代碼
        mc3 = input('是否重新查詢?(yes/no)')
        if mc3 != 'no':     #執(zhí)行yes返回g_by_name,no返回到操作頁面
            update_goods()
        else:
           show_commend()    #返回show_commend()類
 
    else:
        print('==============')
        print('1、修改商品編號')
        print('2、修改商品名稱')
        print('3、修改商品價格')
        print('==============')
        mc2 = int(input('請輸入對應(yīng)的操作號:'))
        if mc2 == 1:
            stuID= input('請輸入修改后的商品編號:')
            a = cursor.execute('update fruits set stuID = %s where stuID= %s', (stuID, cur))
            if a == 1:     #利用游標查找數(shù)據(jù)表,如果數(shù)據(jù)庫中有此表捕獲,沒有報異常
                conn.commit()   #把數(shù)據(jù)傳入數(shù)據(jù)庫
                print('修改成功!')
            else:
                print('修改失?。?)
        elif mc2 == 2:
            stuName = input('請輸入修改后的商品名稱:')
            a = cursor.execute('update fruits set stuName = %s where stuID = %s', (stuName, cur))
            if a >= 1:      #利用游標查找數(shù)據(jù)表,如果數(shù)據(jù)庫中有此表捕獲,沒有報異常
                conn.commit()     #把數(shù)據(jù)傳入數(shù)據(jù)庫
                print('修改成功!')
            else:
                print('修改失??!')
        elif mc2 == 3:
            stuPrice = int(input('請輸入修改后的商品價格:'))
            a = cursor.execute('update fruits set stuPrice= %s where stuID = %s', (stuPrice, cur))
            if a >= 1:      #利用游標查找數(shù)據(jù)表,如果數(shù)據(jù)庫中有此表捕獲,沒有報異常
                conn.commit()     #把數(shù)據(jù)傳入數(shù)據(jù)庫
                print('修改成功!')
            else:
                print('修改失?。?)
        else:
            pass  # 占一個空位符
        show_commend()    #返回show_commend()類

3.1.5 查看超市全部商品

#管理員操作,查詢所有商品信息
def goods_all():
    # 獲取操作游標
    connection = connect()
    conn, cursor = connection['conn'], connection['cursor']
    cursor.execute('select * from fruits')
    fruits = cursor.fetchall()    #利用游標查找數(shù)據(jù)表,如果數(shù)據(jù)庫中有此表捕獲
    print("=============================================")
    print("商品表為:")
    print("=============================================")
    for j in fruits:
        print('---商品編號:{}---商品名稱:{}---商品價格:{}---' .format(j[0], j[1], j[2]))
    print("=============================================")
    show_commend()

3.1.5 制作退出管理員頁面操作端的類

#退出管理員商品管理系統(tǒng)
def end_goods():
    print("已提出!")
    exit()

3.1.6 單個查詢商品方法的選擇器

goods_dict1={'a':g_by_name,'b':g_by_id}
 
#管理員操作,選擇查詢單個商品的方法
def show_querycondition():
    cmd=input("請輸入操作指令:輸入商品名稱查詢(a) 輸入商品編號查詢(b)\n")
    if cmd not in goods_dict1:
        print('輸入錯誤!')
    else:
        goods_dict1[cmd]()  #進入cmd對應(yīng)的values輸出的類中

3.1.7  超市管理員選擇操作類型類

goods_dict2={'a':goods_all,'b':update_goods,'c':add_goods,'d':show_querycondition,'e':delete_goods,'i':end_goods}
#商場工作人員對商品的增刪查改操作
def show_commend():
    cmd=input("請輸入操作指令:查詢?nèi)可唐罚╝) 修改商品(b)  插入商品(c)  查詢單個商品(d)   刪除商品(e)   退出(i)\n")
    if cmd not in goods_dict2:
        print('輸入錯誤!')
        Start()
    else:
        goods_dict2[cmd]()   #進入cmd對應(yīng)的values輸出的類中

3.2 顧客用戶操作端,實現(xiàn)效果:購物車模式,選取商品的種類數(shù)量,結(jié)算,不做長期保存.

3.2.1 將數(shù)據(jù)庫的表轉(zhuǎn)出并轉(zhuǎn)化成指定列表形式

def select_sql():
    # 獲取操作游標
    connection = connect()
    conn, cursor = connection['conn'], connection['cursor']
    sql = "select * from fruits"
    try:                       #利用游標查找數(shù)據(jù)表,如果數(shù)據(jù)庫中有此表捕獲,沒有報異常
        cursor.execute(sql)
        results = cursor.fetchall()
        results=list(results)
        return results
    except Exception as e:    #捕獲異常
        raise e
    finally:
        cursor.close()
        conn.close()
data=select_sql()         #拿到selct_sql元組對象
goods=[]         #利用該空列表把數(shù)據(jù)轉(zhuǎn)移出來
#通過遍歷把selct_sql元組對象轉(zhuǎn)成字典,再轉(zhuǎn)成列表加到goods列表里
for i in data:
    var = {'barcode': i[0], 'product': i[1], 'price': i[2]} #獲取數(shù)據(jù)轉(zhuǎn)成字典
    li=[var]
    goods.extend(li)   #把數(shù)據(jù)加到goods列表里
goods_list=[]    #利用該空列表把數(shù)據(jù)轉(zhuǎn)移出來

3.2.2 超市顧客端首頁

#給顧客展示商店商品信息(進入商店首頁)
def show_list():
    print('序號---------條形碼---------商品名稱---------單價---------數(shù)量---------小計')
    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  將商品添加到購物車

#顧客操作,將商品添加到購物車
def add():
    barcode_add=int(input("請輸入要添加商品的條形碼:"))
    for i in goods:
        if barcode_add==i['barcode']:
            goods_list.append(i)
            numbers_add=int(input("請輸入要購買商品的數(shù)量"))
            sum_add=numbers_add*i.get('price')
            i['number_add']=numbers_add
            i['sum_add']=sum_add
    show_list()    #返回show_list類

3.2.4 修改購物車中的商品

#顧客操作,修改購物車中的商品信息
def edit():
    barcode_edit= int(input("請輸入要修改商品的條形碼:"))
    numbers_edit=int(input("請輸入要修改商品的數(shù)量"))
    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()     #返回show_list類

3.2.5 刪除購物車中的商品

 
#顧客操作,刪除購物車中的商品
def delete():
    barcode_delete = int(input("請輸入要修改商品的條形碼:"))
    for i in goods_list:
        if barcode_delete==i['barcode']:
            goods_list.remove(i)
    show_list()    #返回show_list類

3.2.6 結(jié)算購物車中的商品

#顧客操作,結(jié)算商品
def payment():
    print('-'*100)
    show_list()
    print('-'*100)
    sum=0
    for i in goods_list:
        sum=sum+i['sum_add']
    print("總價為:",sum)
    print("請掃描!")
    print("歡迎下次光臨")
    exit()

3.2.7 制作顧客瀏覽超市商品類

#顧客操作,點擊瀏覽商品信息
def show_goods():
    print("條碼------------商品名稱------------單價")
    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 制作顧客命令操作類

cmd_dict={'a':add,'e':edit,'d':delete,'p':payment,'s':show_goods}
#顧客操作指令
def shopping_commend():
    cmd=input("請輸入操作指令:添加(a) 修改(e)  刪除(d)  結(jié)算(p)  超市商品(s)\n")
    if cmd not in cmd_dict:
        print('輸入錯誤!')
    else:
        cmd_dict[cmd]()        #進入cmd對應(yīng)的values輸出的類中

3.3 登錄端(起始頁登錄(管理員端登錄,顧客端登錄)) 

3.3.1 管理員端登錄類

#商場管理員登錄
def Administrator():
  print("=========================================")
  print("管理員登錄頁面:")
  print("=========================================")
  root = ['aaa', 'bbb', 'ccc', 'ddd', 'fff']
  root_password = ['123', '456', '789', '223', '245']
  a = list(zip(root, root_password))  # 轉(zhuǎn)換為一一對應(yīng)的列表
  num = 0  # 定義一個開始為0的計數(shù)變量
  while True:
      list_1 = input("請管理員姓名:")
      list_1=''.join(list_1.split())  #把輸入的空格去掉,保證在輸入時不會因為名字或密碼字符串里有多余空格而報錯
      l = list_1.split(",")  # 字符串轉(zhuǎn)列表
      list_2 = input("請輸入密碼:")   #把輸入的空格去掉,保證在輸入時不會因為名字或密碼字符串里有多余空格而報錯
      list_2=''.join(list_2.split())
      k = list_2.split(",")
      t = list(zip(l, k))  # 轉(zhuǎn)換為一一對應(yīng)的列表
      c = []  # 定義一個空列表
      for i in range(len(t)):
          c.append(0)
      for i in range(len(a)):  # 對a列表進行遍歷操作,如果a列表中的字符串有一個等于t列表,加入c中
          for j in range(len(t)):
              if a[i] == t[j]:
                  c[j] = c[j] + 1
      text1 = ''.join(str(i) for i in c)  # 由于join里面是字符串類型,讓遍歷和類型轉(zhuǎn)換同步進行
      text1 = int(text1)  # 把text1類型轉(zhuǎn)換為整型*(非0及1)
      if text1 == 1:
          print("登陸成功!")
          while True:
            show_commend()
      else:
          num += 1
          if num < 3:
              print("用戶名或密碼錯誤,請重新輸入:")
          if num >= 3:
              print("用戶名或密碼已經(jīng)錯誤3次,請稍后再試!")
              break

3.3.2 顧客端登錄類

#顧客登錄
def Client():
  name= ['aaa', 'bbb', 'ccc', 'ddd', 'fff']
  name_password = ['123', '456', '789', '223', '245']
  a = list(zip(name, name_password))  # 轉(zhuǎn)換為一一對應(yīng)的列表
  num = 0  # 定義一個開始為0的計數(shù)變量
  print("=========================================")
  print("顧客登錄頁面:")
  print("=========================================")
  while True:
      list_1 = input("請你的姓名:")
      list_1=''.join(list_1.split()) #把輸入的空格去掉,保證在輸入時不會因為名字或密碼字符串里有多余空格而報錯
      l = list_1.split(",")  # 字符串轉(zhuǎn)列表
      list_2 = input("請輸入密碼:")
      list_2=''.join(list_2.split())  #把輸入的空格去掉,保證在輸入時不會因為名字或密碼字符串里有多余空格而報錯
      k = list_2.split(",")
      t = list(zip(l, k))  # 轉(zhuǎn)換為一一對應(yīng)的列表
      c = []  # 定義一個空列表
      for i in range(len(t)):
          c.append(0)
      for i in range(len(a)):  # 對a列表進行遍歷操作,如果a列表中的字符串有一個等于t列表,加入c中
          for j in range(len(t)):
              if a[i] == t[j]:
                  c[j] = c[j] + 1
      text1 = ''.join(str(i) for i in c)  # 由于join里面是字符串類型,讓遍歷和類型轉(zhuǎn)換同步進行
      text1 = int(text1)  # 把text1類型轉(zhuǎn)換為整型*(非0及1)
      if text1 == 1:
          print("登陸成功!")
          print("歡迎光臨來到我的超市")
          print("以下是我的商品清單,請?zhí)暨x:")
          show_goods()
          print("還未購買商品")
          while True:
            shopping_commend()
      else:
          num += 1
          if num < 3:
              print("用戶名或密碼錯誤,請重新輸入:")
          if num >= 3:
              print("用戶名或密碼已經(jīng)錯誤3次,請稍后再試!")
              break

3.3.3 起始頁登錄類,啟動!

#起始頁面
def Start():
    print("=========================================")
    print("歡迎來到XXX商場電子系統(tǒng)!")
    print("=========================================")
    use=int(input("顧客登錄請按1,商場管理員登錄請按2:"))
    if use==1:
        Client()
    else:
        Administrator()
Start() #執(zhí)行Start類

4.實現(xiàn)效果(如下圖)

總結(jié)

到此這篇關(guān)于python操作mysql實現(xiàn)一個超市管理系統(tǒng)的文章就介紹到這了,更多相關(guān)python mysql超市管理系統(tǒng)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python全棧之正則表達式

    Python全棧之正則表達式

    這篇文章主要為大家介紹了Python正則表達式,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2021-11-11
  • Python3合并兩個有序數(shù)組代碼實例

    Python3合并兩個有序數(shù)組代碼實例

    這篇文章主要介紹了Python3合并兩個有序數(shù)組代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-08-08
  • Python實現(xiàn)將絕對URL替換成相對URL的方法

    Python實現(xiàn)將絕對URL替換成相對URL的方法

    這篇文章主要介紹了Python實現(xiàn)將絕對URL替換成相對URL的方法,涉及Python字符串操作及正則匹配的相關(guān)技巧,需要的朋友可以參考下
    2015-06-06
  • 解決Django部署設(shè)置Debug=False時xadmin后臺管理系統(tǒng)樣式丟失

    解決Django部署設(shè)置Debug=False時xadmin后臺管理系統(tǒng)樣式丟失

    這篇文章主要介紹了解決Django部署設(shè)置Debug=False時xadmin后臺管理系統(tǒng)樣式丟失的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • 最新評論