使用mySQL建立简单的数据库
目前创建有三个数据表,剩于用户注册/订单表下次更新。
1.显示所有的商品
2.显示商品id/型号
3.显示商品id/品牌
为什么会有多个表组成数据库,方便:增/删/改/查
from pymysql import connect
class JD(object):
“”“京东商品”“”
def __init__(self):
# 打开数据库连接
self.conn = connect(host="localhost", port=3306, user="root", password="mysql", database="jing_dong",
charset="utf8")
# 使用cursor() 方法创建一个对象cursor
self.cursor = self.conn.cursor()
def __del__(self):
# 关闭数据库连接
self.cursor.close()
self.conn.close()
def show_all_items(self):
"""显示所用商品"""
# 使用execute() 方法执行SQL查询
# 使用 fetchone() 方法获取单条数据
sql = "select * from goods"
self.cursor.execute(sql)
for temp in self.cursor.fetchall():
print(temp)
def show_all_ification(self):
"""显示商品分类"""
sql = "select name from goods_cates"
self.cursor.execute(sql)
for temp in self.cursor.fetchall():
print(temp)
def show_all_brand(self):
"""显示品牌分类"""
sql = "select name from goods_brands"
self.cursor.execute(sql)
for temp in self.cursor.fetchall():
print(temp)
# 使用静态方法
@staticmethod
def print_name():
print("---京东---")
print("1:所有的商品")
print("2:所有的商品分类")
print("3:所有的商品品牌分类")
return input("请输入选项功能:")
def run(self):
while True:
num = self.print_name()
if num == "1":
self.show_all_items()
elif num == "2":
self.show_all_ification()
elif num == "3":
self.show_all_brand()
else:
print("用户输入错误,请重新输入:")
def main():
# 创建一个京东商城对象
jd = JD()
# 调用这个对象的rum方法,让其运行
jd.run()
if name == ‘main‘:
main()