學習pymysql的一個簡單示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
功能:pymysql簡單實例
環境:python3.7
日期:2019/9/9 21:15
作者:指尖魔法師
版本:1.0
"""
from pymysql import connect
class JD(object):
def __init__(self):
self.conn = connect(host='localhost', port=3306, user='root',
password='123456', database='jingdong', charset='utf8')
self.cr = self.conn.cursor()
def __del__(self):
self.cr.close()
self.conn.close()
def execute_sql(self, sql):
"""執行查詢語句"""
self.cr.execute(sql)
result = self.cr.fetchall()
for temp in result:
print(temp)
def show_all_items(self):
"""顯示所有商品"""
sql = 'select * from items;'
self.execute_sql(sql)
def show_cates(self):
"""顯示所有分類"""
sql = 'select * from cates;'
self.execute_sql(sql)
def show_brands(self):
"""顯示所有品牌"""
sql = 'select * from brands;'
self.execute_sql(sql)
def add_item(self):
"""新增商品"""
itemname = input("請輸入商品名稱:")
cateid = int(input("請輸入類別編號:"))
brandid = int(input("請輸入品牌編號:"))
parms = [itemname, cateid, brandid]
sql = 'insert into items values(0,%s,%s,%s);'
self.cr.execute(sql, parms)
self.conn.commit()
def del_item(self):
"""刪除商品"""
itemid = int(input("請輸入需要刪除的商品編號:"))
sql = 'delete from items where id = %s;'
parms = [itemid]
self.cr.execute(sql, parms)
self.conn.commit()
def login(self):
"""登錄判斷"""
ret = False
while True:
user = input("請輸入賬號或'q'退出:")
if user == 'q':
return False
psw = input("請輸入密碼:")
parms = [user]+[psw]
sql = 'select * from admin where username=%s and password=%s;'
self.cr.execute(sql, parms)
ret = self.cr.fetchone()
if ret:
return True
else:
print("賬號或者密碼輸入錯誤,請重新輸入!")
def print_sel(self):
"""打印選擇列表"""
print("---------京東商城產品管理系統--------")
print("1.顯示所有商品")
print("2.顯示所有分類")
print("3.顯示所有品牌")
print("4.新增商品")
print("5.刪除商品")
print("6.退出")
return input("請選擇:")
def run(self):
if self.login():
while True:
num = self.print_sel()
if num == '1':
self.show_all_items()
elif num == '2':
self.show_cates()
elif num == '3':
self.show_brands()
elif num == '4':
self.add_item()
elif num == '5':
self.del_item()
elif num == '6':
exit()
else:
print("輸入錯誤,請重新選擇!")
def main():
jd = JD()
jd.run()
if __name__ == '__main__':
main()
表結構創建語句
create database jingdong charset=utf8;
use jingdong;
create table admin(
id int unsigned auto_increment not null primary key,
username varchar(30) not null,
password varchar(30) not null
);
insert into admin values(0,'admin','admin'),(0,'888','888');
create table items(
id int unsigned auto_increment not null primary key,
itemname varchar(30) not null,
cate int unsigned not null,
brand int unsigned not null
);
insert into items values(0,'神州1號',1,3),(0,'神州2號',2,2),(0,'神州3號',1,4),(0,'神州4號',2,3),(0,'神州5號',3,1);
create table cates(
id int unsigned auto_increment not null primary key,
catename varchar(30) not null
);
insert into cates values(0,'電腦'),(0,'手機'),(0,'相機'),(0,'電風扇');
create table brands(
id int unsigned auto_increment not null primary key,
brandname varchar(30) not null
);
insert into brands values(0,'蘋果'),(0,'魅族'),(0,'諾基亞'),(0,'明基');