练习-商品表的查询

@Software: PyCharm```
‘’’
输入1-查询所有商品
输入2-所有的商品种类
输入3-查询所有的品牌
输入4-退出
‘’’
from pymysql import *

class Jd(object):

def __init__(self):
    # 连接数据库
    self.conn = connect(host='127.0.0.1', port=3306, user='root', passwd='root',
                        db='jd', charset='utf8')
    # 获取游标
    self.cursor = self.conn.cursor()
    
def __del__(self):      
    self.cursor.close()
    self.conn.close()

   
 # 静态方法  不需要self参数
@staticmethod
def print_nemu():
    print('--jd shop--')
    print('1-查询所有商品')
    print('2-所有的商品种类')
    print('3-查询所有的品牌')
    print('4-退出')
    num = input('请输入功能对应的序号:')
    return num

def execute_sql(self,sql):
    # 执行sql
    self.cursor.execute(sql)
    # 获取结果
    result = self.cursor.fetchall()
    for item in result:
        print(item)

def show_all_goods(self):
    sql = 'select * from goods;'
    # self.cursor.execute(sql)
    # result = self.cursor.fetchall()
    # for item in result:
    #     print(item)
    self.execute_sql(sql)

def show_all_cate(self):
    sql = 'select * from goods_cates;'
    # self.cursor.execute(sql)
    # result = self.cursor.fetchall()
    # for item in result:
    #     print(item)
    self.execute_sql(sql)

def show_all_brand(self):
    sql = 'select distinct brand_name from goods;'

    self.execute_sql(sql)

def add_cate(self):
    name = input('输入新商品的分类名字:')
    sql = 'insert into goods_cates(name) values("%s")' % name
    self.cursor.execute(sql)
    self.conn.commit()

def run(self):
    while True:
        num = self.print_nemu()

        if num == '1':
            self.show_all_goods()
        elif num == '2':
            self.show_all_cate()
        elif num == '3':
            self.show_all_brand()
        elif num == '4':               
            break
        elif num == '5':               
            self.add_cate()
        else:
            print('输入有误,请重新输入')

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

if name == ‘main’:
main()


发布了35 篇原创文章 · 获赞 0 · 访问量 530

猜你喜欢

转载自blog.csdn.net/weixin_45905671/article/details/104097171