整理思路
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()