前言
1>项目来自网上一个教学视频,小白博主对其进行了小小的优化,实现了相关密码加密,下订单等相关操作。
一:项目准备
1>数据库准备
这是我为该项目所建的表:
表内数据(因为博主有些私人信息就不公开了,这里给出表的结构:
其中的customer存储用户信息(包含姓名、住址、电话、密码等)。
good_bands存储商品的品牌。
good_cate存储商品的种类。
goods存储商品的具体信息(名称、价格、是否售空、以及库存数量)。
order_information存储订单的订单号,商品以及购买数量。
orders存储顾客的购买时间和昵称。
2>python相关类库的准备:
该项目主要使用了python的pymyql(用于连接mysql)、time(登录时间以及订单号的生成)、hashlib(密码的加密)
第三方库的下载可以使用pip指令也可以在pycharm中直接在python packages点击搜索进行下载。
pip install hashlib
二:项目主要功能介绍
1>数据库基本连接
def __init__(self):
# 产生连接
self.conner = connect(host="localhost", port=3306, user='root', password="liu20020822",
database="python_01", charset='utf8')
# 获得Cursor对象
self.cursor = self.conner.cursor()
num = False
name = ""
passwd = ""
def __del__(self):
self.cursor.close()
self.conner.close()
每次运行时均会对用户昵称和密码进行初始化,其中num用于判断是否进行了登录或者注册等操作。
2>顾客注册以及登录
# 进行注册
def get_index_count(self):
print("--------登录账号--------")
self.name = str(input("请输入你的账号:"))
self.passwd = str(input("请输入你的密码:"))
# 利用类库进行加密
self.passwd = self.passwd.strip()
md5 = hashlib.md5()
md5.update(self.passwd.encode(encoding='utf-8'))
self.passwd = md5.hexdigest()
sql = ('select * from customer where name="%s" and passwd="%s";' % (self.name, self.passwd))
self.cursor.execute(sql)
change = str(self.cursor.fetchone())+"1"
if change == 'None1':
print("登录失败、请核对账号和密码或点击7进行注册")
else:
# 下面这串代码无意义本想删的,但是懒得改了,可以直接用成功替代
sql_user_frequency = "select user_frequency from customer where name ='%s';" % self.name
self.cursor.execute(sql_user_frequency)
good_number_list = list(self.cursor.fetchall())
good_number_tuple = good_number_list[0]
sql_goods_update_number = ("update customer set user_frequency = %d where name='%s';"
% (good_number_tuple[0] + 1, self.name))
self.cursor.execute(sql_goods_update_number)
print("账号登录成功")
self.num = True
self.conner.commit()
# 进行顾客的注册
def get_registered_count(self):
print("--------注册账号--------")
while True:
self.name = str(input("请输入你的昵称:"))
sql_name_search = ('select name from customer where name="%s"' % self.name)
self.cursor.execute(sql_name_search)
if self.cursor.fetchall():
print("此用户名那已经存在,请重新输入")
else:
break
address = str(input("请输入你的家庭地址:"))
telephone = str(input("请输入你的电话:"))
self.passwd = str(input("请输入你的密码:"))
# 密码同样需要加密 以免在登录中进行密码比对中出错(可以写成一个函数的,有点懒)
self.passwd = self.passwd.strip()
md5 = hashlib.md5()
md5.update(self.passwd.encode(encoding='utf-8'))
self.passwd = md5.hexdigest()
sql = "select table_name from information_schema.tables where table_name ='customer';"
if not self.cursor.execute(sql):
sql = """create table if not exists Customer(id int unsigned primary key not null auto_increment,
name varchar(10) not null default "老王",address varchar(30) not null,telephone varchar(11) not null,
passwd varchar(30) not null);"""
self.cursor.execute(sql)
sql = ('insert into Customer values(0,"%s","%s",%s,"%s");' % (self.name, address, telephone, self.passwd))
self.cursor.execute(sql)
print("表单注册成功")
else:
sql = ('insert into Customer values( 0, "%s", "%s", %s, "%s", 0 );'
% (self.name, address, telephone, self.passwd))
self.cursor.execute(sql)
print("成功注册")
# 将num属性进行更改
self.num = True
self.conner.commit()
3>商品品牌等展示
# 这些是表中数据的一些查询,随手写写就好
def show_all_items(self):
sql = 'select name from goods;'
self.execute_sql(sql)
def show_all_bands(self):
sql = 'select name from good_cate;'
self.execute_sql(sql)
def show_all_type(self):
sql = 'select band from good_bands;'
self.execute_sql(sql)
4>下订单
def get_info_sold(self):
print("--------开始下订单--------")
# 下订单的时间
now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
customer_name = self.name
# 订单号,用时间数据代替,第一个使用年是为了防止重复(写文章的时候才改的,,)
order_number = str(time.strftime('%Y%M%S', time.localtime(time.time()))
+ str(time.time()).replace('.', '')[-7:])
good = input("请输入要购买的商品:")
number = eval(input("请输入要购买的数量:"))
# 首先判断商品是否存在在goods表中是否存在该商品
sql = "select name from goods where name='%s';" % good
if self.cursor.execute(sql):
# 查询表是否存在,当时傻逼了,其实都应该表是提前建好的,省去这个步骤
sql = "select table_name from information_schema.tables where table_name ='orders';"
if self.cursor.execute(sql):
sql_good_number = "select number from goods where name ='%s';" % good
self.cursor.execute(sql_good_number)
good_number_list = list(self.cursor.fetchall())
good_number_tuple = good_number_list[0]
if good_number_tuple[0]-number > 0:
sql_goods_update_number = ("update goods set number=%d where name='%s';"
% (good_number_tuple[0] - number, good))
sql_good_insert = ("insert into Orders values(0,'%s','%s');" % (now_time, customer_name))
self.cursor.execute(sql_good_insert)
self.cursor.execute(sql_goods_update_number)
sql_good_information_insert = ("insert into Order_Information values(0,'%s','%s','%s');"
% (order_number, good, number))
self.cursor.execute(sql_good_information_insert)
print("购买成功")
else:
print("该商品货物不足,只有%d件了" % (good_number_tuple[0]))
else:
# 这里就是建表
sql_good_create = """create table if not exists Orders(id int unsigned not null auto_increment
primary key,date_time datetime not null,customer varchar(30) not null)"""
self.cursor.execute(sql_good_create)
sql_good_information_create = """create table if not exists Order_Information(id int unsigned primary
key not null auto_increment,order_number varchar(30) not null default "8888888",
goods varchar(15) not null,number int unsigned not null default 0);"""
self.cursor.execute(sql_good_information_create)
sql_good_insert = ("insert into Orders values(0,'%s','%s');" % (now_time, customer_name))
self.cursor.execute(sql_good_insert)
sql_good_information_insert = ("insert into Order_Information values(0,'%s','%s','%s');"
% (order_number, good, number))
self.cursor.execute(sql_good_information_insert)
print("该表成功创建")
self.conner.commit()
else:
print("商品不存在")
5>主函数调用
def run(self):
while True:
print("--------京东商城--------\n\n"+"--------1.0 所有的商品名称\n"+"--------2.0 所有的商品品牌\n"
+ "--------3.0 所有的商品属性\n"+"--------4.0 添加一个商品 ")
print("--------5.0 根据名字查询商品\n"+"--------6.0 登录账号\n"+"--------7.0 注册账号\n"+"--------8.0 下订单\n"+"--------0 退出")
select = eval(input("请输入功能对应选项:\n"))
if select == 1: # 查询所有的商品名称
if self.num:
self.show_all_items()
else:
print("请重新登录")
elif select == 2: # 查询你所有商品品牌
if self.num:
self.show_all_bands()
else:
print("请重新登录")
elif select == 3: # 查询你所有的商品属性
if self.num:
self.show_all_type()
else:
print("请重新登录")
elif select == 4:
if self.num:
self.get_add_type()
else:
print("请重新登录")
elif select == 5:
if self.num:
self.get_info_by_name()
else:
print("请重新登录")
elif select == 6:
self.get_index_count()
elif select == 7:
self.get_registered_count()
elif select == 8:
if self.num:
self.get_info_sold()
else:
print("请重新登录")
elif select == 0:
break
else:
print("输入错误 请重新输入 或重新登录")
我使用了简单的选择,字典也可以,有点冗余了。
三:完整源码附录:
from pymysql import *
import time
import hashlib
class Good(object):
def __init__(self):
# 产生连接
self.conner = connect(host="localhost", port=3306, user='root', password="liu20020822",
database="python_01", charset='utf8')
# 获得Cursor对象
self.cursor = self.conner.cursor()
num = False
name = ""
passwd = ""
def __del__(self):
self.cursor.close()
self.conner.close()
def execute_sql(self, sql):
self.cursor.execute(sql)
for temp in self.cursor.fetchall():
print(temp)
def show_all_items(self):
sql = 'select name from goods;'
self.execute_sql(sql)
def show_all_bands(self):
sql = 'select name from good_cate;'
self.execute_sql(sql)
def show_all_type(self):
sql = 'select band from good_bands;'
self.execute_sql(sql)
def get_add_type(self):
item = input("输入待加入的商品名称:")
cate_id = eval(input("请输入品牌id:(数字)"))
brand_id = input("请输入品牌属性id:")
price = eval(input("请输入价格:"))
number = eval(input("请输入代售数量:"))
sql = ("""insert into goods values(0,"%s","%d","%s","%d",default,default,"%d")"""
% (item, cate_id, brand_id, price, number))
self.cursor.execute(sql)
self.conner.commit()
def get_info_by_name(self):
item = input("输入待搜查的商品品牌名称:")
sql = "select * from goods where name=%s;"
self.cursor.execute(sql, [item]) # 执行sql语句、同时防止sql语句注入
print(self.cursor.fetchall())
def get_index_count(self):
print("--------登录账号--------")
self.name = str(input("请输入你的账号:"))
self.passwd = str(input("请输入你的密码:"))
self.passwd = self.passwd.strip()
md5 = hashlib.md5()
md5.update(self.passwd.encode(encoding='utf-8'))
self.passwd = md5.hexdigest()
sql = ('select * from customer where name="%s" and passwd="%s";' % (self.name, self.passwd))
self.cursor.execute(sql)
change = str(self.cursor.fetchone())+"1"
if change == 'None1':
print("登录失败、请核对账号和密码或点击7进行注册")
else:
sql_user_frequency = "select user_frequency from customer where name ='%s';" % self.name
self.cursor.execute(sql_user_frequency)
good_number_list = list(self.cursor.fetchall())
good_number_tuple = good_number_list[0]
sql_goods_update_number = ("update customer set user_frequency = %d where name='%s';"
% (good_number_tuple[0] + 1, self.name))
self.cursor.execute(sql_goods_update_number)
print("账号登录成功")
self.num = True
self.conner.commit()
def get_registered_count(self):
# 如果不存在创建一个新表、填充顾客的id(不进行手动输入自动进行填充) 呢称 住址 电话 密码
# 如果存在则只有填充不新建
print("--------注册账号--------")
while True:
self.name = str(input("请输入你的昵称:"))
sql_name_search = ('select name from customer where name="%s"' % self.name)
self.cursor.execute(sql_name_search)
if self.cursor.fetchall():
print("此用户名那已经存在,请重新输入")
else:
break
address = str(input("请输入你的家庭地址:"))
telephone = str(input("请输入你的电话:"))
self.passwd = str(input("请输入你的密码:"))
self.passwd = self.passwd.strip()
md5 = hashlib.md5()
md5.update(self.passwd.encode(encoding='utf-8'))
self.passwd = md5.hexdigest()
sql = "select table_name from information_schema.tables where table_name ='customer';"
if not self.cursor.execute(sql):
sql = """create table if not exists Customer(id int unsigned primary key not null auto_increment,
name varchar(10) not null default "老王",address varchar(30) not null,telephone varchar(11) not null,
passwd varchar(30) not null);"""
self.cursor.execute(sql)
sql = ('insert into Customer values(0,"%s","%s",%s,"%s");' % (self.name, address, telephone, self.passwd))
self.cursor.execute(sql)
print("表单注册成功")
else:
sql = ('insert into Customer values( 0, "%s", "%s", %s, "%s", 0 );'
% (self.name, address, telephone, self.passwd))
self.cursor.execute(sql)
print("成功注册")
self.num = True
self.conner.commit()
def get_info_sold(self):
print("--------开始下订单--------")
now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
customer_name = self.name
order_number = str(time.strftime('%H%M%S', time.localtime(time.time()))
+ str(time.time()).replace('.', '')[-7:])
# 首次创建订单表和订单详情表、两表存在关联同时存在或者消失 id 订单号 时间 顾客 均自动生成、选填数量和商品
good = input("请输入要购买的商品:")
number = eval(input("请输入要购买的数量:"))
# 首先判断商品是否存在在goods表中是否存在该商品
sql = "select name from goods where name='%s';" % good
if self.cursor.execute(sql):
sql = "select table_name from information_schema.tables where table_name ='orders';"
if self.cursor.execute(sql):
sql_good_number = "select number from goods where name ='%s';" % good
self.cursor.execute(sql_good_number)
good_number_list = list(self.cursor.fetchall())
good_number_tuple = good_number_list[0]
if good_number_tuple[0]-number > 0:
sql_goods_update_number = ("update goods set number=%d where name='%s';"
% (good_number_tuple[0] - number, good))
sql_good_insert = ("insert into Orders values(0,'%s','%s');" % (now_time, customer_name))
self.cursor.execute(sql_good_insert)
self.cursor.execute(sql_goods_update_number)
sql_good_information_insert = ("insert into Order_Information values(0,'%s','%s','%s');"
% (order_number, good, number))
self.cursor.execute(sql_good_information_insert)
print("购买成功")
else:
print("该商品货物不足,只有%d件了" % (good_number_tuple[0]))
else:
sql_good_create = """create table if not exists Orders(id int unsigned not null auto_increment
primary key,date_time datetime not null,customer varchar(30) not null)"""
self.cursor.execute(sql_good_create)
sql_good_information_create = """create table if not exists Order_Information(id int unsigned primary
key not null auto_increment,order_number varchar(30) not null default "8888888",
goods varchar(15) not null,number int unsigned not null default 0);"""
self.cursor.execute(sql_good_information_create)
sql_good_insert = ("insert into Orders values(0,'%s','%s');" % (now_time, customer_name))
self.cursor.execute(sql_good_insert)
sql_good_information_insert = ("insert into Order_Information values(0,'%s','%s','%s');"
% (order_number, good, number))
self.cursor.execute(sql_good_information_insert)
print("该表成功创建")
self.conner.commit()
else:
print("商品不存在")
def run(self):
while True:
print("--------京东商城--------\n\n"+"--------1.0 所有的商品名称\n"+"--------2.0 所有的商品品牌\n"
+ "--------3.0 所有的商品属性\n"+"--------4.0 添加一个商品 ")
print("--------5.0 根据名字查询商品\n"+"--------6.0 登录账号\n"+"--------7.0 注册账号\n"+"--------8.0 下订单\n"+"--------0 退出")
select = eval(input("请输入功能对应选项:\n"))
if select == 1: # 查询所有的商品名称
if self.num:
self.show_all_items()
else:
print("请重新登录")
elif select == 2: # 查询你所有商品品牌
if self.num:
self.show_all_bands()
else:
print("请重新登录")
elif select == 3: # 查询你所有的商品属性
if self.num:
self.show_all_type()
else:
print("请重新登录")
elif select == 4:
if self.num:
self.get_add_type()
else:
print("请重新登录")
elif select == 5:
if self.num:
self.get_info_by_name()
else:
print("请重新登录")
elif select == 6:
self.get_index_count()
elif select == 7:
self.get_registered_count()
elif select == 8:
if self.num:
self.get_info_sold()
else:
print("请重新登录")
elif select == 0:
break
else:
print("输入错误 请重新输入 或重新登录")
def main():
client = Good()
client.run()
if __name__ == '__main__':
main()
结束语:博主的第一篇,以后还会继续写作,如果上述项目有不同见解的,欢迎大家在评论区或者私聊我。