python 操做mysql數據庫之模擬購物系統登陸及購物,功能包含普通用戶、管理員登陸,查看商品、購買商品、添加商品,用戶充值等。python
mysql 數據庫shop 表結構建立以下:mysql
create TABLE userinfo ( u_id int(10) not null auto_increment, u_name varchar(35), u_passwd varchar(35), money decimal(10,2), role int(5), primary key(u_id) )CHARACTER set utf8 COLLATE utf8_general_ci; CREATE TABLE product( p_id int(10) NOT NULL auto_increment, p_name VARCHAR(35), p_price DECIMAL(10,2), PRIMARY KEY (p_id) )CHARACTER SET utf8 COLLATE utf8_general_ci; create table carts( c_id int(10) not null auto_increment, u_id int(10) NOT null, p_id int(10) NOT null, PRIMARY key (c_id) )CHARACTER SET utf8 COLLATE utf8_general_ci;
初始化插入的數據以下:sql
insert into userinfo (u_name,u_passwd,money,role)VALUES('sp1','123456',100000.55,1); insert into userinfo (u_name,u_passwd,money,role)VALUES('sp3','111222',100000.55,1); insert into userinfo (u_name,u_passwd,money,role)VALUES('sp3','123456',100000.55,1); insert into product(p_name,p_price) values('MI',1999.00); insert into product(p_name,p_price) values('MAC',1999.00); insert into product(p_name,p_price) values('iphoneX',1999.00); insert into product(p_name,p_price) values('VIVO',1999.00);
項目結構以下: 數據庫
confsetting.py 爲配置文件,存放系統常量:iphone
HOST = '172.16.2.163' USER = 'root' PASSWD = '123456' DB_NAME = 'shop'
lib目錄下存放系統功能和經常使用函數:函數
mysql.py內容:fetch
def op_mysql(host,user,passwd,db,sql,charset='utf8',port=3306): "操做數據庫" import pymysql from pymysql.cursors import DictCursor coon = pymysql.connect(host=host,user=user,passwd=passwd,db=db,charset=charset,port=port) cur = coon.cursor(DictCursor) # 定義一個遊標,返回一個字典類型 cur.execute(sql) if sql.strip().startswith('select'): res = cur.fetchall() else: coon.commit() res = 'ok' cur.close() coon.close() return res
action.py內容:spa
from conf.confsetting import HOST,USER,PASSWD,DB_NAME from lib.mysql import op_mysql def login(u_name, u_pass): "用戶登陸" name = str(u_name) passwd = str(u_pass) res = None if not name or not passwd: print("error,用戶名或密碼不能爲空!") else: my_sql = "select u.u_id,u.u_name,u.u_passwd,u.money,u.role from userinfo u where u.u_name='%s';" % name user_info = op_mysql(host=HOST, user=USER, passwd=PASSWD, db=DB_NAME, sql=my_sql) if len(user_info) == 0: print('error,用戶名不存在') else: for u in user_info: # 可能存在同名 if u['u_passwd'] == passwd: print('用戶:{u} 登陸成功!'.format(u=u)) res = u if not res: print('error,密碼輸入錯誤') return res def get_goods(): "查詢全部商品" my_sql = "select p.* from product p;" goods_info = op_mysql(host=HOST, user=USER, passwd=PASSWD, db=DB_NAME, sql=my_sql) print('success,查詢全部商品成功,商品信息:', goods_info) return goods_info def bug_goods(u_info, g_name): "用戶購買商品" res =None g_name = str(g_name) if not g_name : print('購買商品名稱不能爲空!') else: goods_info = get_goods() for i in range(len(goods_info)): if goods_info[i]['p_name'] == g_name: if u_info['money'] < goods_info[i]['p_price']: res = '餘額不足購買商品失敗!', goods_info[i] else: new_money = u_info['money'] - goods_info[i]['p_price'] new_money =round(new_money,2) my_sql_1 = "update userinfo set money = '%d' where u_id = '%d';"%(new_money,u_info['u_id']) my_sql_2 = "INSERT INTO carts (u_id,p_id) VALUES('%d','%d');"%(u_info['u_id'],goods_info[i]['p_id']) op_mysql(host=HOST, user=USER, passwd=PASSWD, db=DB_NAME, sql=my_sql_1) op_mysql(host=HOST, user=USER, passwd=PASSWD, db=DB_NAME, sql=my_sql_2) res = '購買商品成功!', goods_info[i] if not res: res = 'error ,購買商品%s不存在'% g_name return res def get_carts_money(u_id): "查詢用戶購物車、餘額" my_sql = "select u.money from userinfo u where u.u_id ='%d';"% u_id u_money = op_mysql(host=HOST, user=USER, passwd=PASSWD, db=DB_NAME, sql=my_sql) my_sql = "select p.p_name from userinfo u ,carts c ,product p where u.u_id='%d'and u.u_id =c.u_id and c.p_id= p.p_id; "%u_id u_cart = op_mysql(host=HOST, user=USER, passwd=PASSWD, db=DB_NAME, sql=my_sql) return "帳戶餘額:{m} 購物車:{c}".format(m =u_money,c =u_cart) def add_goods(g_name, g_price): "添加商品" if not g_name: return 'error,添加商品失敗,商品名稱必須輸入' price = round(float(g_price), 2) if price <= 0: return 'error,添加商品失敗,商品價格須大於0' my_sql = "insert into product(p_name,p_price) values('%s','%s');"%(g_name,g_price) op_mysql(host=HOST, user=USER, passwd=PASSWD, db=DB_NAME, sql=my_sql) return 'success,添加商品:%s成功'% g_name def recharge(u_id, amount): "輸入用戶ID給用戶充值" u_id = int(u_id) u_amount = round(float(amount), 2) if u_amount <= 0: return 'error,充值金額須大於0' my_sql = "select u.u_name,u.money from userinfo u where u.u_id ='%d';" % u_id user_info = op_mysql(host=HOST, user=USER, passwd=PASSWD, db=DB_NAME, sql=my_sql) if len(user_info) == 0: return '用戶id不存在' new_money = user_info[0]['money'] + u_amount my_sql = "update userinfo set money = '%d' where u_id = '%d';"%(new_money,u_id) op_mysql(host=HOST, user=USER, passwd=PASSWD, db=DB_NAME, sql=my_sql) return 'success,給用戶:%s 充值%s 元 成功'% (user_info[0]['u_name'],u_amount)
menu.py 內容:code
from lib.action import get_goods,bug_goods,get_carts_money,add_goods,recharge def role_1(user): "普通用戶菜單" choice = input('請輸入你的選擇:1:查看全部商品 2:購買商品 3:查看購物車和餘額 4:退出\n').strip() if choice == '1': print(get_goods()) elif choice == '2': goods_name = input("請輸入要購買商品名稱:\n").strip() print(bug_goods(user, goods_name)) elif choice == '3': print(get_carts_money(user['u_id'])) elif choice == '4': exit('退出程序') role_1(user) def role_2(user): "管理員菜單" choice = input('請輸入你的選擇:1:添加商品 2:給用戶充值 3:退出\n').strip() if choice == '1': goods_name = input("請輸入你要添加的商品名稱:\n").strip() goods_price = input("請輸入添加商品價格:\n").strip() print(add_goods(goods_name, goods_price)) elif choice == '2': u_id = input("請輸入你要充值的用戶id:\n").strip() amount = input("請輸入充值金額:\n").strip() print(recharge(u_id, amount)) elif choice == '3': exit('退出程序') role_2(user)
bin 目錄下存放啓動文件:orm
start.py內容:
import os,sys cur_path = os.path.abspath(__file__) base_path = os.path.dirname(os.path.dirname(cur_path)) sys.path.insert(0,base_path) from lib.action import login from lib.menu import role_1,role_2 uName = input("請輸入登陸用戶名:\n").strip() uPass = input("請輸入登陸密碼:\n").strip() user = login(uName, uPass) if user: # 用戶登陸成功 # 普通用戶: if user['role'] == 1: role_1(user) # 管理員用戶: elif user['role'] == 2: role_2(user) else: print("用戶角色不存在") else: print("用戶還沒有登陸")
運行結果以下: