MySQL 与 Python 交互之牛刀小试

查询jing_dong数据库中的数据,实现如下功能:

1:所有的商品 (goods【id、商品名称、分类id、品牌id、价格、是否显示】)

2:所有的商品分类  (goods_cates【id、分类名称】)

3:所有的商品品牌  (goods_brands【id、品牌名称】)

在此基础上,实现如下功能:

商品分类的添加、修改、删除、查找

商品品牌的添加、修改、删除、查找

商品的添加、修改、删除、查找

退出

附加题1:实现登录注册,用户表user【id、用户名、密码、地址、电话】

附加题2:实现下订单功能。包含两张表:

        订单表order【id、订单号、用户id】

        订单详情表order_list【id、订单id、商品id、购买数量】

数据准备:参考《MySQL 与 Python 交互之数据库准备

另外还需创建以下几个数据表:

用户表user【id、用户名、密码、地址、电话】

create table userinfo(id int unsigned not null primary key auto_increment,
name varchar(50) not null,
password varchar(100) not null,
address varchar(50) not  null,
TEL varchar(12) not null);

向数据表中插入数据:

insert into userinfo value
(0,  "老王", "laowang", "河南省焦作市", "18849529357"),
(0,  "老李", "laoli", "河南省郑州市", "18849522222"),
(0,  "张三", "zhangsan", "河南省平顶山市", "18849523333"),
(0,  "李四", "lisi", "河北省石家庄市", "18849524444"),
(0,  "王五", "wangwu", "河南省洛阳市", "18849525555"),
(0,  "赵六", "zhaoliu", "北京市", "18849526666");

订单表orders【id、订单号、用户id】

create table orders(id int unsigned not null primary key auto_increment,
order_datetime datetime not null,
user_id int unsigned not null);

订单详情表order_list【id、订单id、商品id、购买数量】

create table order_list(id int unsigned not null primary key auto_increment,
order_id int unsigned not null,
goods_id int unsigned not null,
quantity int unsigned not null default 1);

代码实现:

from pymysql import connect
import time


class JD:
    def __init__(self):
        # 1.创建 connect 链接
        self.conn = connect(host="127.0.0.1", port=3306, user="root", password="mysql",
                            database="jing_dong", charset="utf8")
        # 2.获得 cursor 对象
        self.cs = self.conn.cursor()
        # 用户姓名
        self.user_name = None

    def __del__(self):
        self.cs.close()
        self.conn.close()

    def execute_sql(self, sql):
        self.cs.execute(sql)
        for data in self.cs.fetchall():
            print(data)

    def show_goods(self):
        """所有的商品"""
        sql = "select * from goods"
        self.execute_sql(sql)

    def show_cates(self):
        """所有的商品分类"""
        sql = "select name from goods_cates"
        self.execute_sql(sql)

    def show_brands(self):
        """所有的商品品牌分类"""
        sql = "select name from goods_brands"
        self.execute_sql(sql)

    def add_cate(self):
        """添加商品类别"""
        add_data = input("请输入要添加的商品类别:")
        sql = "insert into goods_cates (name) values ('%s')" % add_data
        self.cs.execute(sql)
        self.conn.commit()

    def find_goods_by_name(self):
        """根据商品名称查询信息"""
        find_name = input("请输入您要查询的商品名称:")
        sql = "select * from goods where name = %s"
        self.cs.execute(sql, [find_name])
        print(self.cs.fetchall())

    def find_goods_by_id(self):
        """根据商品名称查询信息"""
        find_name = input("请输入您要查询的商品id:")
        sql = "select * from goods where id = %s"
        self.cs.execute(sql, [find_name])
        print(self.cs.fetchall())

    def add_brand(self):
        """添加商品品牌"""
        add_data = input("请输入要添加的商品品牌:")
        sql = "insert into goods_brands (name) values ('%s')" % add_data
        self.cs.execute(sql)
        self.conn.commit()

    def del_cate(self):
        """删除商品类别"""
        del_data = input("请输入要删除的商品类别:")
        sql = "delete from goods_cates where name = %s"
        self.cs.execute(sql, [del_data])
        self.conn.commit()

    def del_brand(self):
        """删除商品品牌"""
        del_data = input("请输入要删除的商品品牌:")
        sql = "delete from goods_brands where name = %s"
        self.cs.execute(sql, [del_data])
        self.conn.commit()

    def change_cate(self):
        """修改商品类别"""
        change_data = input("请输入要修改的商品类别:")
        changed_data = input("请输入修改后的商品类别:")
        sql = "update goods_cates set name = %s where name =%s"
        self.cs.execute(sql, [changed_data, change_data])
        self.conn.commit()

    def change_brand(self):
        """修改商品品牌"""
        change_data = input("请输入要修改的商品品牌:")
        changed_data = input("请输入修改后的商品品牌:")
        sql = "update goods_brands set name = %s where name =%s"
        self.cs.execute(sql, [changed_data, change_data])
        self.conn.commit()

    def add_good(self):
        """添加商品"""
        # TODO 设置 id 限制
        name = input("请输入要添加的商品名称:")
        cate_id = input("请输入要添加的商品类别id:")
        brand_id = input("请输入要添加的商品品牌id:")
        price = input("请输入要添加的商品价格:")
        sql = "insert into goods (name, cate_id, brand_id, price) values(%s, %s, %s, %s)"
        self.cs.execute(sql, [name, cate_id, brand_id, price])
        self.conn.commit()

    def change_good_by_name(self):
        """根据名称修改商品"""
        name = input("请输入要修改商品的名称:")
        field = input("请输入要修改的字段:")
        u_name = input("请输入修改后的结果:")
        # TODO 如何防止 SQL 注入
        sql = "update goods set %s='%s' where name='%s'" % (field, u_name, name)
        # print("--->%s<---" % sql)
        self.cs.execute(sql)
        # sql = "update goods set %s=%s where name=%s"
        # self.cs.execute(sql, [field, u_name, name])
        # print("--->%s<---" % sql, [field, u_name, name])
        self.conn.commit()

    def change_good_by_id(self):
        """根据id修改商品"""
        name = input("请输入要修改商品的id:")
        field = input("请输入要修改的字段:")
        u_name = input("请输入修改后的结果:")
        # TODO 如何防止 SQL 注入
        sql = "update goods set %s='%s' where id='%s'" % (field, u_name, name)
        # print("--->%s<---" % sql)
        # sql = "update goods set %s= %s where id= %s"
        # self.cs.execute(sql, [field, u_name, name])
        self.cs.execute(sql)
        self.conn.commit()

    def del_good_by_name(self):
        """根据名称删除商品"""
        name = input("请输入要删除商品的名称:")
        sql = "delete from goods where name=%s"
        self.cs.execute(sql, [name])
        self.conn.commit()

    def del_good_by_id(self):
        """根据id删除商品"""
        name = input("请输入要删除商品的id:")
        sql = "delete from goods where id=%s"
        self.cs.execute(sql, [name])
        self.conn.commit()

    def enter(self):
        """登录"""
        self.user_name = input("请输入您的用户名:")
        user_passward = input("请输入您的密码:")
        # 把用户名设置为 唯一索引 确保用户名唯一
        sql = "select password from userinfo where name = %s"
        self.cs.execute(sql, [self.user_name])
        if user_passward == self.cs.fetchone()[0]:
            print("登录成功")
        else:
            print("登录失败")
            self.user_name = None

    def register(self):
        """注册"""
        name = input("请输入您的用户名:")
        password = input("请输入您的密码:")
        address = input("请输入您的地址:")
        tel = input("请输入您的联系方式:")
        sql = "insert into userinfo (name, password, address, TEL) values(%s, %s, %s, %s)"
        self.cs.execute(sql, [name, password, address, tel])
        self.conn.commit()
        print("注册成功")

    def find_user_id(self, user_name):
        sql = "select id from userinfo where name = %s"
        self.cs.execute(sql, [user_name])
        user_id = self.cs.fetchone()[0]
        return user_id

    def creat_order(self):
        print("***********下订单操作*************")
        # print(self.user_name)
        if self.user_name:
            # 获取顾客 id
            user_id = self.find_user_id(self.user_name)
            # 添加订单
            order_id = self.add_order(user_id)
            good_id = input("请您输入您要购买的商品id:")
            quantity = input("请您输入您要购买的商品数量:")
            # 添加订单详情
            self.add_order_list(order_id, good_id, quantity)
        else:
            print("登录后才能下订单!")

    def add_order(self, user_id):
        order_datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        sql = "insert into orders (order_datetime, user_id) values(%s, %s)"
        self.cs.execute(sql, [order_datetime, user_id])
        self.conn.commit()
        sql = "select id from orders where order_datetime = %s"
        self.cs.execute(sql, [order_datetime])
        order_id = self.cs.fetchone()[0]
        return order_id

    def add_order_list(self, order_id, goods_id, quantity):
        sql = "insert into order_list (order_id, goods_id, quantity) values(%s, %s, %s)"
        self.cs.execute(sql, [order_id, goods_id, quantity])
        self.conn.commit()

    @staticmethod
    def print_menu():
        print("***********京东商城*************")
        print("1:增加")
        print("2:修改")
        print("3:删除")
        print("4:查找")
        print("5:登录注册")
        print("6:下订单")
        print("0:退出")
        menu = input("请输入功能对应的序号:")
        return menu

    @staticmethod
    def print_c():
        print("***********增加操作*************")
        print("1:添加商品类别")
        print("2:添加商品品牌")
        print("3:添加商品")
        print("0:返回上一级")
        num = input("请输入功能对应的序号:")
        return num

    @staticmethod
    def print_u():
        print("***********修改操作*************")
        print("1:修改商品类别")
        print("2:修改商品品牌")
        print("3:根据商品名称修改商品")
        print("4:根据商品id修改商品")
        print("0:返回上一级")
        num = input("请输入功能对应的序号:")
        return num

    @staticmethod
    def print_d():
        print("***********删除操作*************")
        print("1:删除商品类别")
        print("2:删除商品品牌")
        print("3:通过商品名称删除商品")
        print("4:通过商品id删除商品")
        print("0:返回上一级")
        num = input("请输入功能对应的序号:")
        return num

    @staticmethod
    def print_r():
        print("***********查找操作*************")
        print("1:查看商品类别")
        print("2:查看商品品牌")
        print("3:查看所有商品")
        print("4:通过商品名称查看商品")
        print("5:通过商品id查看商品")
        print("0:返回上一级")
        num = input("请输入功能对应的序号:")
        return num

    @staticmethod
    def login():
        print("**********登录操作*************")
        print("1:登录")
        print("2:注册")
        print("0:返回上一级")
        num = input("请输入功能对应的序号:")
        return num

    def run(self):
        while True:
            menu = JD.print_menu()
            if menu == "1":
                while True:
                    num = JD.print_c()
                    if num == "1":
                        self.add_cate()
                    elif num == "2":
                        self.add_brand()
                    elif num == "3":
                        self.add_good()
                    elif num == "0":
                        break
                    else:
                        print("输入有误,请重新输入。。。")

            elif menu == "2":
                while True:
                    num = JD.print_u()
                    if num == "1":
                        self.change_cate()
                    elif num == "2":
                        self.change_brand()
                    elif num == "3":
                        self.change_good_by_name()
                    elif num == "4":
                        self.change_good_by_id()
                    elif num == "0":
                        break
                    else:
                        print("输入有误,请重新输入。。。")

            elif menu == "3":
                while True:
                    num = JD.print_d()
                    if num == "1":
                        self.del_cate()
                    elif num == "2":
                        self.del_brand()
                    elif num == "3":
                        self.del_good_by_name()
                    elif num == "4":
                        self.del_good_by_id()
                    elif num == "0":
                        break
                    else:
                        print("输入有误,请重新输入。。。")

            elif menu == "4":
                while True:
                    num = JD.print_r()
                    if num == "1":
                        self.show_cates()
                    elif num == "2":
                        self.show_brands()
                    elif num == "3":
                        self.show_goods()
                    elif num == "4":
                        self.find_goods_by_name()
                    elif num == "5":
                        self.find_goods_by_id()
                    elif num == "0":
                        break
                    else:
                        print("输入有误,请重新输入。。。")

            elif menu == "5":
                while True:
                    num = JD.login()
                    if num == "1":
                        self.enter()
                    elif num == "2":
                        self.register()
                    elif num == "0":
                        break
                    else:
                        print("输入有误,请重新输入。。。")

            elif menu == "6":
                # 创建订单
                self.creat_order()

            elif menu == "0":
                break

            else:
                print("输入有误,请重新输入。。。")


def main():
    jd = JD()
    jd.run()


if __name__ == "__main__":
    main()

猜你喜欢

转载自blog.csdn.net/apollo_miracle/article/details/81809837