整理思路
1.导入from pymysql import *
(下载pymsql,终端中输入pip3 install pymysql)
2.建立类,和函数根据已经创建过的数据库和优化后coding
class JD(object):
def __init__(self):
# 创建Connection连接
self.conn = connect(
host='localhost',
port=3306,
database='jing_dong',
user='root',
password='mysql',
charset='utf8')
# 获得Cursor对象
self.csl = self.conn.cursor()
def __del__(self):
# 关闭
self.csl.close()
self.conn.close()
def execute_sql(self,sql):
self.csl.execute(sql)
for temp in self.csl.fetchall():
print(temp)
def show_all_items(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_brands(self,name):
# name = input('请输入要输入的商品名称')
sql = "insert into goods_brands(name) values('%s')" % name
self.csl.execute(sql)
self.conn.commit()
# @staticmethod
# def print_menu(self):
def run(self):
while True:
print('--京东--')
print('1.所有的物品')
print('2.所有的物品分类')
print('3.所有物品品牌分类')
print('4.添加物品品牌')
num = input('请输入功能对应的序号')
if num == '1':
# 所有的物品
self.show_all_items()
elif num == '2':
# 所有的物品分类
self.show_cates()
elif num == '3':
# 3.所有物品品牌分类
self.show_brands()
elif num == '4':
# 3.添加物品品牌
name = input("请输入你要添加的商品名称")
self.add_brands(name)
else:
print('输入错误')
def main():
# 创建一个京东对象
jd = JD()
jd.run()
if __name__ == '__main__':
main()