Python操做MySQL數據庫完成簡易的增刪改查功能

說明:該篇博客是博主一字一碼編寫的,實屬不易,請尊重原創,謝謝你們!python

目錄mysql

一丶項目介紹linux

二丶效果展現sql

三丶數據準備數據庫

四丶代碼實現ubuntu

五丶完整代碼小程序


一丶項目介紹

1.敘述服務器

博主閒暇之餘花了10個小時寫的小程序,對於python操做數據庫不太會的同窗,很值得學習參考app

經過python與mysql數據庫的交互來模擬京東商城,代碼邏輯就是對商品進行添加,修改,查詢,以及刪除操做,很是簡單。ide

2.項目環境

操做系統:Linux(ubuntu)

IDE:PyCharm2018

數據庫:MySQL

Python版本:3.5

二丶效果展現

說明:博主這裏只是展現了查詢功能中的單個商品信息查詢,當查詢商品不存在時,則會提示用戶

運行程序----選擇1商品查詢功能----選擇0查詢單個商品信息----顯示查詢到幾條數據----顯示詳情數據----顯示查詢功能菜單----選擇4返回主功能菜單----跳轉到主功能菜單

*******歡迎來到京東商城(主功能菜單)*******
                   1.商品查詢功能
                   2.商品添加功能
                   3.商品修改功能
                   4.商品刪除功能
                   5.退出程序
            
請選擇功能序號:1

            *******歡迎來到京東商城(查詢功能)*******
                   0.查詢單個商品信息
                   1.查詢全部的商品信息
                   2.查詢商品分類信息
                   3.查詢全部的品牌分類信息
                   4.返回主功能菜單
            
請選擇查詢功能序號:0
請輸入要查找商品名字:x
一共查詢到5條記錄
(2, 'x550cc 15.6英寸筆記本', 5, 2, Decimal('2799.000'), b'\x01', b'\x00')
(3, 'x240 超極本', 7, 7, Decimal('4880.000'), b'\x01', b'\x00')
(12, 'at7-7414lp 臺式電腦 linux )', 1, 3, Decimal('3699.000'), b'\x01', b'\x00')
(18, 'x3250 m4機架式服務器', 3, 1, Decimal('6888.000'), b'\x01', b'\x00')
(21, '華碩 ROG玩家國度GFX72 17英寸遊戲 筆記本', 4, 2, Decimal('32998.000'), b'\x01', b'\x00')

            *******歡迎來到京東商城(查詢功能)*******
                   0.查詢單個商品信息
                   1.查詢全部的商品信息
                   2.查詢商品分類信息
                   3.查詢全部的品牌分類信息
                   4.返回主功能菜單
            
請選擇查詢功能序號:4

            *******歡迎來到京東商城(主功能菜單)*******
                   1.商品查詢功能
                   2.商品添加功能
                   3.商品修改功能
                   4.商品刪除功能
                   5.退出程序
            
請選擇功能序號:5
程序正在退出,請稍候....

Process finished with exit code 0

三丶數據準備

1.建立數據庫jing_dong

create database jing_dong charset = utf8;

2.在jing_dong數據庫中建立goods表

create table goods(
    id int unsigned primary key auto_increment not null,
    name varchar(150) not null,
    cate_id int(10) unsigned not null,
    brand_id int(10) unsigned not null,
    price decimal(10,3) not null default 0,
    is_show bit not null default 1,
    is_saleoff bit not null default 0
);

3.向goods商品信息表中插入如下數據

說明:其實除了goods商品信息表之外,還有goods_ctaes商品分類表以及goods_brands商品品牌表,在goods表中的cate_id以及brand_id都是指向這兩張表中的主鍵id,由於博主在這裏只是針對goods商品信息表進行增刪改查,因此這裏不須要用到那兩張表

insert into goods values(0,'r510vc 15.6英寸筆記本',5,2,'3399',default,default); 
insert into goods values(0,'y400n 14.0英寸筆記本電腦',5,7,'4999',default,default);
insert into goods values(0,'g150th 15.6英寸遊戲本',4,9,'8499',default,default); 
insert into goods values(0,'x550cc 15.6英寸筆記本',5,2,'2799',default,default); 
insert into goods values(0,'x240 超極本',7,7,'4880',default,default); 
insert into goods values(0,'u330p 13.3英寸超極本',7,7,'4299',default,default); 
insert into goods values(0,'svp13226scb 觸控超極本',7,6,'7999',default,default); 
insert into goods values(0,'ipad mini 7.9英寸平板電腦',2,8,'1998',default,default);
insert into goods values(0,'ipad air 9.7英寸平板電腦',2,8,'3388',default,default); 
insert into goods values(0,'ipad mini 配備 retina 顯示屏',2,8,'2788',default,default); 
insert into goods values(0,'ideacentre c340 20英寸一體電腦 ',1,7,'3499',default,default); 
insert into goods values(0,'vostro 3800-r1206 臺式電腦',1,5,'2899',default,default); 
insert into goods values(0,'imac me086ch/a 21.5英寸一體電腦',1,8,'9188',default,default); 
insert into goods values(0,'at7-7414lp 臺式電腦 linux )',1,3,'3699',default,default); 
insert into goods values(0,'z220sff f4f06pa工做站',3,4,'4288',default,default); 
insert into goods values(0,'poweredge ii服務器',3,5,'5388',default,default); 
insert into goods values(0,'mac pro專業級臺式電腦',3,8,'28888',default,default); 
insert into goods values(0,'hmz-t3w 頭戴顯示設備',6,6,'6999',default,default); 
insert into goods values(0,'商務雙肩揹包',6,6,'99',default,default); 
insert into goods values(0,'x3250 m4機架式服務器',3,1,'6888',default,default); 
insert into goods values(0,'商務雙肩揹包',6,6,'99',default,default);

四丶代碼實現

1.業務邏輯分爲三層,第一層負責顯示主功能菜單,第二層分爲(增刪改查)功能菜單,第三層詳細功能實現

2.代碼塊說明:

class JD:具體業務代碼邏輯實現,完成鏈接本地數據庫,對數據庫中的goods表數據進行增刪改查業務操做

class Menu:功能界面選項打印顯示

def select_main:查詢功能主業務邏輯

def add_main:增長功能主業務邏輯

def update_main:修改功能主業務邏輯

def delete_main:刪除功能主業務邏輯

def main:主功能業務邏輯

3.main方法代碼實現

def main():
    """主功能菜單"""
    while True:
        Menu.print_main_menu()
        num = input("請選擇功能序號:")
        if num == "1":
            select_main()
        elif num == "2":
            add_main()
        elif num == "3":
            update_main()
        elif num == "4":
            delete_main()
        elif num == "5":
            JD().close_database()
            print("程序正在退出,請稍候....")
            time.sleep(2)
            break
        else:
            print("您的輸入不正確,請從新輸入!")

4.select_main方法代碼實現

def select_main():
    """查詢商品信息功能"""
    while True:
        Menu.print_select_menu()
        num = input("請選擇查詢功能序號:")
        if num == "0":
            find_name = input("請輸入要查找商品名字:")
            find_name = "%" + find_name + "%"
            result, count = JD().select_single_good(find_name)
            if result is not None:
                print("一共查詢到%s條記錄" % count)
                for res in result:
                    print(res)
            else:
                print("對不起!您輸入的商品不存在...")
        elif num == "1":
            temps, count = JD().select_all_goods()
            print("一共查詢到%s個商品" % count)
            for temp in temps:
                print(temp)
        elif num == "2":
            result, count = JD().select_goods_class()
            print("一共查詢到%s類商品" % count)
            print(result)
        elif num == "3":
            result, count = JD().select_goods_logo()
            print("一共查詢到有%s種品牌" % count)
            print(result)
        elif num == "4":
            break
        else:
            print("輸入不正確,請從新輸入!")

5.add_main方法代碼實現

def add_main():
"""添加商品信息功能"""
    while True:
        Menu.print_add_menu()
        num = input("請選擇增長功能序號:")
        if num == "1":
            good_name = input("請輸入商品名字:")
            while True:
                Menu.print_goods_cates()
                good_cate = input("請選擇商品分類:")
                if good_cate in("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"):
                    good_cate = int(good_cate)
                    break
                else:
                    print("輸入不正確,請從新輸入!")
            while True:
                Menu.print_goods_brands()
                good_brand = input("請選擇商品品牌:")
                if good_brand in("1", "2", "3", "4", "5", "6", "7", "8", "9"):
                    good_brand = int(good_brand)
                    break
                else:
                    print("輸入不正確,請從新輸入!")
            good_price = float(input("請輸入商品價格:"))
            JD().add_single_good(good_name, good_cate, good_brand, good_price)
        elif num == "2":
            break
        else:
            print("輸入錯誤,請從新輸入!")

6.update_main方法代碼實現

def update_main():
    """修改商品信息功能"""
    while True:
        Menu.print_update_menu()
        num = input("請選擇修改功能序號:")
        if num == "1":
            ids = list()
            for data in JD().get_goods_ids():
                for id in data:
                    ids.append(id)
            good_id_name = input("請輸入要修改商品的編號或名字:")
            try:
                if int(good_id_name) in ids:
                    # 表示輸入了正確的商品編號
                    JD().update_single_good(0, good_id_name)  # 0表示用戶輸入的是商品編號,不然表示商品名字
                else:
                    while True:
                        new_id = input("您輸入的商品編號不存在,請從新輸入:")
                        if int(new_id) in ids:
                            break
                    JD().update_single_good(0, new_id)
            except Exception as e:
                JD().update_single_good(e, good_id_name)
        elif num == "2":
            break
        else:
            print("輸入錯誤,請從新輸入!")

7.delete_main方法代碼實現

def delete_main():
    """刪除商品信息功能"""
    while True:
        Menu.print_delete_menu()
        num = input("請選擇刪除功能序號:")
        if num == "1":
            ids = list()
            for data in JD().get_goods_ids():
                for id in data:
                    ids.append(id)
            print("全部商品信息以下:")
            for good in JD().get_goods_id_name():
                print(good)
            while True:
                good_id = input("請輸入要刪除的商品編號:")
                try:
                    if int(good_id) in ids:
                        JD().delete_single_good(good_id)
                        break
                    else:
                        print("您輸入的商品編號不存在,請從新輸入:")
                except Exception as e:
                    print("非法輸入", e)

        elif num == "2":
            temps, count = JD().select_all_goods()
            print("一共有%s種商品信息" % count)
            for temp in temps:
                print(temp)
            num = input("1.點錯了 2.繼續刪除:")
            if num == "1":
                break
            elif num == "2":
                s = input("數據刪除後將沒法恢復,確認請輸入y:").lower()
                if s == "y":
                    JD().delete_all_goods()
            else:
                print("輸入錯誤,操做取消中....")
                time.sleep(1)
                break
        elif num == "3":
            break
        else:
            print("輸入錯誤,請從新輸入!")

8.Menu類代碼實現

class Menu(object):
    """界面信息打印顯示"""
    @staticmethod
    def print_main_menu():
        print(
            """
            *******歡迎來到京東商城(主功能菜單)*******
                   1.商品查詢功能
                   2.商品添加功能
                   3.商品修改功能
                   4.商品刪除功能
                   5.退出程序
            """
        )

    @staticmethod
    def print_select_menu():
        print(
            """
            *******歡迎來到京東商城(查詢功能)*******
                   0.查詢單個商品信息
                   1.查詢全部的商品信息
                   2.查詢商品分類信息
                   3.查詢全部的品牌分類信息
                   4.返回主功能菜單
            """
        )

    @staticmethod
    def print_add_menu():
        print(
            """
            *******歡迎來到京東商城(增長功能)*******
                   1.添加商品信息
                   2.返回主功能菜單
            """
        )

    @staticmethod
    def print_update_menu():
        print(
            """
            *******歡迎來到京東商城(修改功能)*******
                   1.修改單個商品信息
                   2.返回主功能菜單
            """
        )

    @staticmethod
    def print_delete_menu():
        print(
            """
            *******歡迎來到京東商城(刪除功能)*******
                   1.刪除單個商品信息
                   2.刪除全部的商品信息
                   3.返回主功能菜單
            """
        )

    @staticmethod
    def print_goods_cates():
        print(
            """
        ******商品分類******
            1.臺式機             
            2.平板電腦           
            3.服務器/工做站       
            4.遊戲本              
            5.筆記本             
            6.筆記本配件         
            7.超級本             
            8.硬盤               
            9.光盤               
            10.顯示器       
            """
        )

    @staticmethod
    def print_goods_brands():
        print(
            """
     ******商品品牌******
            1.ibm
            2.華碩  
            3.宏碁 
            4.惠普
            5.戴爾
            6.索尼
            7.聯想 
            8.蘋果  
            9.雷神        
            """
        )

9.JD類代碼實現

class JD(object):
    def __init__(self):
        """初始化 鏈接數據庫"""
        self.conn = connect(host="localhost",
                            port=3306,
                            user="root",
                            password="mysql",
                            database="jing_dong",
                            charset="utf8"
                            )
        self.cursors = self.conn.cursor()

    def select_single_good(self, find_name):
        """查詢單個商品信息"""
        count = self.cursors.execute("select * from goods where name like '%s'" % find_name)
        if count != 0:
            return self.cursors.fetchall(), count
        else:
            return None

    def select_all_goods(self):
        """查詢全部商品信息"""
        count = self.cursors.execute("select * from goods")
        return self.cursors.fetchall(), count

    def select_goods_class(self):
        """查詢商品分類"""
        count = self.cursors.execute("select name from goods_cates")
        return self.cursors.fetchall(), count

    def select_goods_logo(self):
        """查詢商品品牌"""
        count = self.cursors.execute("select name from goods_brands")
        return self.cursors.fetchall(), count

    def add_single_good(self, name, cate, brand, price):
        """添加單個商品信息"""
        # sql = ("insert into goods(name,cate_id,brand_id,price)values(%s,%d,%d,%s) " % (name, cate, brand, price))
        count = self.cursors.execute("insert into goods (name,cate_id,brand_id,price) values ('%s',%d,%d,%f) " % (name, cate, brand, price))
        if count == 1:
            print("添加商品信息成功....")
            self.conn.commit()
            self.cursors.execute("select * from goods where name = '%s'" % name)
            print(self.cursors.fetchone())
        else:
            print("添加商品信息失敗....")

        # self.cursors.execute("insert into goods()")

    def get_goods_ids(self):
        """獲取全部商品的id編號"""
        self.cursors.execute("select id from goods")
        return self.cursors.fetchall()

    def get_goods_id_name(self):
        """獲取全部商品的編號以名稱"""
        self.cursors.execute("select id,name from goods order by id")
        return self.cursors.fetchall()

    @staticmethod
    def get_user_update_data():
        """獲取用戶修改的商品信息"""
        flag = True  # 設置開關 當用戶輸入的商品信息項不存在時則爲False
        data = dict()
        index = list()
        while True:
            print("1.商品名稱 2.商品分類 3.商品品牌 4.商品價格")
            user_choose = input("請選擇要修改的商品信息項:")
            if not len(user_choose) > 4 or len(user_choose) < 1:
                break
        for i in user_choose:
            if i == "1":
                u_name = input("請輸入修改後的商品名稱:")
                data["name"] = u_name
                index.append(i)
            elif i == "2":
                Menu.print_goods_cates()
                try:
                    u_cate = int(input("請輸入修改後的商品分類編號:"))
                    data["cate_id"] = u_cate
                    index.append(i)
                except Exception as e:
                    print("您輸入的商品分類編號錯誤", e)
                    return
            elif i == "3":
                Menu.print_goods_brands()
                try:
                    u_brand = int(input("請輸入修改後的商品品牌編號:"))
                    data["brand_id"] = u_brand
                    index.append(i)
                except Exception as e:
                    print("您輸入的商品品牌編號錯誤", e)
                    return
            elif i == "4":
                try:
                    u_price = float(input("請輸入修改後的商品價格:"))
                    data["price"] = u_price
                    index.append(i)
                except Exception as e:
                    print("您輸入的商品價格錯誤", e)
                    return
            else:
                flag = False
                print("您輸入的商品信息項目含有非法輸入(%s)" % i)
        if flag:
            return index, data  # {'brand_id': 2, 'cate_id': 2, 'name': 'ssss'}

    def update_single_good(self, sign, name_id):
        """修改商品信息"""
        # 1.根據用戶輸入的查詢條件,獲取商品信息並顯示到客戶窗口上
        if 0 == sign:
            good_id = name_id
            self.cursors.execute("select * from goods where id = '%s'" % good_id)
            # 由於在update_main方法中已經對商品編號進行判斷,用戶輸入的商品編號在數據庫中能找到才能調用此方法
            print(self.cursors.fetchone())
            index, data = JD().get_user_update_data()
            if index:
                for i in index:
                    if i == "1":
                        key1 = "name"
                        count = self.cursors.execute(
                            "update goods set %s = '%s' where id = '%s'" % (key1, data[key1], good_id))
                        if count == 1:
                            print("修改商品名稱成功!")
                            self.conn.commit()
                        else:
                            print("修改商品名稱失敗!")
                            return
                    elif i == "2":
                        key2 = "cate_id"
                        count = self.cursors.execute(
                            "update goods set %s = '%s' where id = '%s'" % (key2, data[key2], good_id))
                        if count == 1:
                            print("修改商品分類成功!")
                            self.conn.commit()
                        else:
                            print("修改商品分類失敗!")
                            return
                    elif i == "3":
                        key3 = "brand_id"
                        count = self.cursors.execute(
                            "update goods set %s = '%s' where id = '%s'" % (key3, data[key3], good_id))
                        if count == 1:
                            print("修改商品品牌成功!")
                            self.conn.commit()
                        else:
                            print("修改商品品牌失敗!")
                            return
                    elif i == "4":
                        key4 = "price"
                        count = self.cursors.execute(
                            "update goods set %s = '%s' where id = '%s'" % (key4, data[key4], good_id))
                        if count == 1:
                            print("修改商品價格成功!")
                            self.conn.commit()
                        else:
                            print("修改商品價格失敗!")
                            return
                # 2.根據用戶選擇商品修改項對其進行修改,將修改爲功後的商品信息展示出來
                self.cursors.execute("select * from goods where id = '%s'" % good_id)
                print(self.cursors.fetchone())
            else:
                print("用戶未選擇")
                return
        else:
            good_name = name_id
            count = self.cursors.execute("select * from goods where name = '%s'" % good_name)
            good_id = int  # 用於保存商品編碼,由於編碼是惟一不能修改的
            if count != 0:
                for i in self.cursors.fetchone():
                    good_id = i
                    break
                index, data = JD().get_user_update_data()
                if index:
                    for i in index:
                        if i == "1":
                            key1 = "name"
                            count = self.cursors.execute(
                                "update goods set %s = '%s' where name = '%s'" % (key1, data[key1], good_name))
                            if count == 1:
                                print("修改商品名稱成功!")
                                self.conn.commit()
                            else:
                                print("修改商品名稱失敗!")
                                return
                        elif i == "2":
                            key2 = "cate_id"
                            count = self.cursors.execute(
                                "update goods set %s = '%s' where name = '%s'" % (key2, data[key2], good_name))
                            if count == 1:
                                print("修改商品分類成功!")
                                self.conn.commit()
                            else:
                                print("修改商品分類失敗!")
                                return
                        elif i == "3":
                            key3 = "brand_id"
                            count = self.cursors.execute(
                                "update goods set %s = '%s' where name = '%s'" % (key3, data[key3], good_name))
                            if count == 1:
                                print("修改商品品牌成功!")
                                self.conn.commit()
                            else:
                                print("修改商品品牌失敗!")
                                return
                        elif i == "4":
                            key4 = "price"
                            count = self.cursors.execute(
                                "update goods set %s = '%s' where name = '%s'" % (key4, data[key4], good_name))
                            if count == 1:
                                print("修改商品價格成功!")
                                self.conn.commit()
                            else:
                                print("修改商品價格失敗!")
                                return
                    self.cursors.execute("select * from goods where id = '%s'" % good_id)
                    print(self.cursors.fetchone())
                else:
                    print("用戶未選擇")
                    return
            else:
                new_name = input("您輸入的商品名稱不存在,請從新輸入:")
                self.update_single_good(1, new_name)

    def delete_single_good(self, good_id):
        """刪除單個商品信息"""
        count = self.cursors.execute("delete from goods where id = '%s'" % good_id)
        if count == 1:
            print("刪除商品信息成功!")
            self.conn.commit()
        else:
            print("刪除商品信息失敗!")
            return

    def delete_all_goods(self):
        """刪除全部商品信息"""
        count = self.cursors.execute("truncate table goods")
        if count == 0:
            print("全部商品信息已所有刪除")

    def close_database(self):
        """關閉數據庫鏈接對象以及遊標對象"""
        self.cursors.close()
        self.conn.close()

五丶完整代碼

from pymysql import *
import time


class JD(object):
    def __init__(self):
        """初始化 鏈接數據庫"""
        self.conn = connect(host="localhost",
                            port=3306,
                            user="root",
                            password="mysql",
                            database="jing_dong",
                            charset="utf8"
                            )
        self.cursors = self.conn.cursor()

    def select_single_good(self, find_name):
        """查詢單個商品信息"""
        count = self.cursors.execute("select * from goods where name like '%s'" % find_name)
        if count != 0:
            return self.cursors.fetchall(), count
        else:
            return None

    def select_all_goods(self):
        """查詢全部商品信息"""
        count = self.cursors.execute("select * from goods")
        return self.cursors.fetchall(), count

    def select_goods_class(self):
        """查詢商品分類"""
        count = self.cursors.execute("select name from goods_cates")
        return self.cursors.fetchall(), count

    def select_goods_logo(self):
        """查詢商品品牌"""
        count = self.cursors.execute("select name from goods_brands")
        return self.cursors.fetchall(), count

    def add_single_good(self, name, cate, brand, price):
        """添加單個商品信息"""
        # sql = ("insert into goods(name,cate_id,brand_id,price)values(%s,%d,%d,%s) " % (name, cate, brand, price))
        count = self.cursors.execute("insert into goods (name,cate_id,brand_id,price) values ('%s',%d,%d,%f) " % (name, cate, brand, price))
        if count == 1:
            print("添加商品信息成功....")
            self.conn.commit()
            self.cursors.execute("select * from goods where name = '%s'" % name)
            print(self.cursors.fetchone())
        else:
            print("添加商品信息失敗....")

        # self.cursors.execute("insert into goods()")

    def get_goods_ids(self):
        """獲取全部商品的id編號"""
        self.cursors.execute("select id from goods")
        return self.cursors.fetchall()

    def get_goods_id_name(self):
        """獲取全部商品的編號以名稱"""
        self.cursors.execute("select id,name from goods order by id")
        return self.cursors.fetchall()

    @staticmethod
    def get_user_update_data():
        """獲取用戶修改的商品信息"""
        flag = True  # 設置開關 當用戶輸入的商品信息項不存在時則爲False
        data = dict()
        index = list()
        while True:
            print("1.商品名稱 2.商品分類 3.商品品牌 4.商品價格")
            user_choose = input("請選擇要修改的商品信息項:")
            if not len(user_choose) > 4 or len(user_choose) < 1:
                break
        for i in user_choose:
            if i == "1":
                u_name = input("請輸入修改後的商品名稱:")
                data["name"] = u_name
                index.append(i)
            elif i == "2":
                Menu.print_goods_cates()
                try:
                    u_cate = int(input("請輸入修改後的商品分類編號:"))
                    data["cate_id"] = u_cate
                    index.append(i)
                except Exception as e:
                    print("您輸入的商品分類編號錯誤", e)
                    return
            elif i == "3":
                Menu.print_goods_brands()
                try:
                    u_brand = int(input("請輸入修改後的商品品牌編號:"))
                    data["brand_id"] = u_brand
                    index.append(i)
                except Exception as e:
                    print("您輸入的商品品牌編號錯誤", e)
                    return
            elif i == "4":
                try:
                    u_price = float(input("請輸入修改後的商品價格:"))
                    data["price"] = u_price
                    index.append(i)
                except Exception as e:
                    print("您輸入的商品價格錯誤", e)
                    return
            else:
                flag = False
                print("您輸入的商品信息項目含有非法輸入(%s)" % i)
        if flag:
            return index, data  # {'brand_id': 2, 'cate_id': 2, 'name': 'ssss'}

    def update_single_good(self, sign, name_id):
        """修改商品信息"""
        # 1.根據用戶輸入的查詢條件,獲取商品信息並顯示到客戶窗口上
        if 0 == sign:
            good_id = name_id
            self.cursors.execute("select * from goods where id = '%s'" % good_id)
            # 由於在update_main方法中已經對商品編號進行判斷,用戶輸入的商品編號在數據庫中能找到才能調用此方法
            print(self.cursors.fetchone())
            index, data = JD().get_user_update_data()
            if index:
                for i in index:
                    if i == "1":
                        key1 = "name"
                        count = self.cursors.execute(
                            "update goods set %s = '%s' where id = '%s'" % (key1, data[key1], good_id))
                        if count == 1:
                            print("修改商品名稱成功!")
                            self.conn.commit()
                        else:
                            print("修改商品名稱失敗!")
                            return
                    elif i == "2":
                        key2 = "cate_id"
                        count = self.cursors.execute(
                            "update goods set %s = '%s' where id = '%s'" % (key2, data[key2], good_id))
                        if count == 1:
                            print("修改商品分類成功!")
                            self.conn.commit()
                        else:
                            print("修改商品分類失敗!")
                            return
                    elif i == "3":
                        key3 = "brand_id"
                        count = self.cursors.execute(
                            "update goods set %s = '%s' where id = '%s'" % (key3, data[key3], good_id))
                        if count == 1:
                            print("修改商品品牌成功!")
                            self.conn.commit()
                        else:
                            print("修改商品品牌失敗!")
                            return
                    elif i == "4":
                        key4 = "price"
                        count = self.cursors.execute(
                            "update goods set %s = '%s' where id = '%s'" % (key4, data[key4], good_id))
                        if count == 1:
                            print("修改商品價格成功!")
                            self.conn.commit()
                        else:
                            print("修改商品價格失敗!")
                            return
                # 2.根據用戶選擇商品修改項對其進行修改,將修改爲功後的商品信息展示出來
                self.cursors.execute("select * from goods where id = '%s'" % good_id)
                print(self.cursors.fetchone())
            else:
                print("用戶未選擇")
                return
        else:
            good_name = name_id
            count = self.cursors.execute("select * from goods where name = '%s'" % good_name)
            good_id = int  # 用於保存商品編碼,由於編碼是惟一不能修改的
            if count != 0:
                for i in self.cursors.fetchone():
                    good_id = i
                    break
                index, data = JD().get_user_update_data()
                if index:
                    for i in index:
                        if i == "1":
                            key1 = "name"
                            count = self.cursors.execute(
                                "update goods set %s = '%s' where name = '%s'" % (key1, data[key1], good_name))
                            if count == 1:
                                print("修改商品名稱成功!")
                                self.conn.commit()
                            else:
                                print("修改商品名稱失敗!")
                                return
                        elif i == "2":
                            key2 = "cate_id"
                            count = self.cursors.execute(
                                "update goods set %s = '%s' where name = '%s'" % (key2, data[key2], good_name))
                            if count == 1:
                                print("修改商品分類成功!")
                                self.conn.commit()
                            else:
                                print("修改商品分類失敗!")
                                return
                        elif i == "3":
                            key3 = "brand_id"
                            count = self.cursors.execute(
                                "update goods set %s = '%s' where name = '%s'" % (key3, data[key3], good_name))
                            if count == 1:
                                print("修改商品品牌成功!")
                                self.conn.commit()
                            else:
                                print("修改商品品牌失敗!")
                                return
                        elif i == "4":
                            key4 = "price"
                            count = self.cursors.execute(
                                "update goods set %s = '%s' where name = '%s'" % (key4, data[key4], good_name))
                            if count == 1:
                                print("修改商品價格成功!")
                                self.conn.commit()
                            else:
                                print("修改商品價格失敗!")
                                return
                    self.cursors.execute("select * from goods where id = '%s'" % good_id)
                    print(self.cursors.fetchone())
                else:
                    print("用戶未選擇")
                    return
            else:
                new_name = input("您輸入的商品名稱不存在,請從新輸入:")
                self.update_single_good(1, new_name)

    def delete_single_good(self, good_id):
        """刪除單個商品信息"""
        count = self.cursors.execute("delete from goods where id = '%s'" % good_id)
        if count == 1:
            print("刪除商品信息成功!")
            self.conn.commit()
        else:
            print("刪除商品信息失敗!")
            return

    def delete_all_goods(self):
        """刪除全部商品信息"""
        count = self.cursors.execute("truncate table goods")
        if count == 0:
            print("全部商品信息已所有刪除")

    def close_database(self):
        """關閉數據庫鏈接對象以及遊標對象"""
        self.cursors.close()
        self.conn.close()


class Menu(object):
    """界面信息打印顯示"""
    @staticmethod
    def print_main_menu():
        print(
            """
            *******歡迎來到京東商城(主功能菜單)*******
                   1.商品查詢功能
                   2.商品添加功能
                   3.商品修改功能
                   4.商品刪除功能
                   5.退出程序
            """
        )

    @staticmethod
    def print_select_menu():
        print(
            """
            *******歡迎來到京東商城(查詢功能)*******
                   0.查詢單個商品信息
                   1.查詢全部的商品信息
                   2.查詢商品分類信息
                   3.查詢全部的品牌分類信息
                   4.返回主功能菜單
            """
        )

    @staticmethod
    def print_add_menu():
        print(
            """
            *******歡迎來到京東商城(增長功能)*******
                   1.添加商品信息
                   2.返回主功能菜單
            """
        )

    @staticmethod
    def print_update_menu():
        print(
            """
            *******歡迎來到京東商城(修改功能)*******
                   1.修改單個商品信息
                   2.返回主功能菜單
            """
        )

    @staticmethod
    def print_delete_menu():
        print(
            """
            *******歡迎來到京東商城(刪除功能)*******
                   1.刪除單個商品信息
                   2.刪除全部的商品信息
                   3.返回主功能菜單
            """
        )

    @staticmethod
    def print_goods_cates():
        print(
            """
        ******商品分類******
            1.臺式機             
            2.平板電腦           
            3.服務器/工做站       
            4.遊戲本              
            5.筆記本             
            6.筆記本配件         
            7.超級本             
            8.硬盤               
            9.光盤               
            10.顯示器       
            """
        )

    @staticmethod
    def print_goods_brands():
        print(
            """
     ******商品品牌******
            1.ibm
            2.華碩  
            3.宏碁 
            4.惠普
            5.戴爾
            6.索尼
            7.聯想 
            8.蘋果  
            9.雷神        
            """
        )


def select_main():
    """查詢商品信息功能"""
    while True:
        Menu.print_select_menu()
        num = input("請選擇查詢功能序號:")
        if num == "0":
            find_name = input("請輸入要查找商品名字:")
            find_name = "%" + find_name + "%"
            result, count = JD().select_single_good(find_name)
            if result is not None:
                print("一共查詢到%s條記錄" % count)
                for res in result:
                    print(res)
            else:
                print("對不起!您輸入的商品不存在...")
        elif num == "1":
            temps, count = JD().select_all_goods()
            print("一共查詢到%s個商品" % count)
            for temp in temps:
                print(temp)
        elif num == "2":
            result, count = JD().select_goods_class()
            print("一共查詢到%s類商品" % count)
            print(result)
        elif num == "3":
            result, count = JD().select_goods_logo()
            print("一共查詢到有%s種品牌" % count)
            print(result)
        elif num == "4":
            break
        else:
            print("輸入不正確,請從新輸入!")


def add_main():
    """添加商品信息功能"""
    while True:
        Menu.print_add_menu()
        num = input("請選擇增長功能序號:")
        if num == "1":
            good_name = input("請輸入商品名字:")
            while True:
                Menu.print_goods_cates()
                good_cate = input("請選擇商品分類:")
                if good_cate in("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"):
                    good_cate = int(good_cate)
                    break
                else:
                    print("輸入不正確,請從新輸入!")
            while True:
                Menu.print_goods_brands()
                good_brand = input("請選擇商品品牌:")
                if good_brand in("1", "2", "3", "4", "5", "6", "7", "8", "9"):
                    good_brand = int(good_brand)
                    break
                else:
                    print("輸入不正確,請從新輸入!")
            good_price = float(input("請輸入商品價格:"))
            JD().add_single_good(good_name, good_cate, good_brand, good_price)
        elif num == "2":
            break
        else:
            print("輸入錯誤,請從新輸入!")


def update_main():
    """修改商品信息功能"""
    while True:
        Menu.print_update_menu()
        num = input("請選擇修改功能序號:")
        if num == "1":
            ids = list()
            for data in JD().get_goods_ids():
                for id in data:
                    ids.append(id)
            good_id_name = input("請輸入要修改商品的編號或名字:")
            try:
                if int(good_id_name) in ids:
                    # 表示輸入了正確的商品編號
                    JD().update_single_good(0, good_id_name)  # 0表示用戶輸入的是商品編號,不然表示商品名字
                else:
                    while True:
                        new_id = input("您輸入的商品編號不存在,請從新輸入:")
                        if int(new_id) in ids:
                            break
                    JD().update_single_good(0, new_id)
            except Exception as e:
                JD().update_single_good(e, good_id_name)
        elif num == "2":
            break
        else:
            print("輸入錯誤,請從新輸入!")


def delete_main():
    """刪除商品信息功能"""
    while True:
        Menu.print_delete_menu()
        num = input("請選擇刪除功能序號:")
        if num == "1":
            ids = list()
            for data in JD().get_goods_ids():
                for id in data:
                    ids.append(id)
            print("全部商品信息以下:")
            for good in JD().get_goods_id_name():
                print(good)
            while True:
                good_id = input("請輸入要刪除的商品編號:")
                try:
                    if int(good_id) in ids:
                        JD().delete_single_good(good_id)
                        break
                    else:
                        print("您輸入的商品編號不存在,請從新輸入:")
                except Exception as e:
                    print("非法輸入", e)

        elif num == "2":
            temps, count = JD().select_all_goods()
            print("一共有%s種商品信息" % count)
            for temp in temps:
                print(temp)
            num = input("1.點錯了 2.繼續刪除:")
            if num == "1":
                break
            elif num == "2":
                s = input("數據刪除後將沒法恢復,確認請輸入y:").lower()
                if s == "y":
                    JD().delete_all_goods()
            else:
                print("輸入錯誤,操做取消中....")
                time.sleep(1)
                break
        elif num == "3":
            break
        else:
            print("輸入錯誤,請從新輸入!")


def main():
    """主功能菜單"""
    while True:
        Menu.print_main_menu()
        num = input("請選擇功能序號:")
        if num == "1":
            select_main()
        elif num == "2":
            add_main()
        elif num == "3":
            update_main()
        elif num == "4":
            delete_main()
        elif num == "5":
            JD().close_database()
            print("程序正在退出,請稍候....")
            time.sleep(2)
            break
        else:
            print("您的輸入不正確,請從新輸入!")


if __name__ == '__main__':
    main()
相關文章
相關標籤/搜索