前言

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 = Falsename = ""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.nameself.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 = Trueself.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:breakaddress = 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 = Trueself.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';" % goodif 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';" % goodself.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:breakelse:print("输入错误 请重新输入 或重新登录")

我使用了简单的选择,字典也可以,有点冗余了。

三:完整源码附录:

from pymysql import *
import time
import hashlibclass 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 = Falsename = ""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.nameself.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 = Trueself.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:breakaddress = 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 = Trueself.conner.commit()def get_info_sold(self):print("--------开始下订单--------")now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())customer_name = self.nameorder_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';" % goodif 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';" % goodself.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:breakelse:print("输入错误 请重新输入 或重新登录")def main():client = Good()client.run()if __name__ == '__main__':main()

结束语:博主的第一篇,以后还会继续写作,如果上述项目有不同见解的,欢迎大家在评论区或者私聊我。

京东商城(mysql+python)相关推荐

  1. python爬虫完整实例-python爬虫实战之爬取京东商城实例教程

    前言 本文主要介绍的是利用python爬取京东商城的方法,文中介绍的非常详细,下面话不多说了,来看看详细的介绍吧. 主要工具 scrapy BeautifulSoup requests 分析步骤 1. ...

  2. 爬虫python的爬取步骤-python爬虫实战之爬取京东商城实例教程

    前言 本文主要介绍的是利用python爬取京东商城的方法,文中介绍的非常详细,下面话不多说了,来看看详细的介绍吧. 主要工具 scrapy BeautifulSoup requests 分析步骤 1. ...

  3. python爬虫爬图片教程_python爬虫实战之爬取京东商城实例教程

    前言 本文主要介绍的是利用python爬取京东商城的方法,文中介绍的非常详细,下面话不多说了,来看看详细的介绍吧. 主要工具 scrapy BeautifulSoup requests 分析步骤 1. ...

  4. python 爬网站 实例_python爬虫实战:之爬取京东商城实例教程!(含源代码)

    前言: 本文主要介绍的是利用python爬取京东商城的方法,文中介绍的非常详细,下面话不多说了,来看看详细的介绍吧. 主要工具 scrapy BeautifulSoup requests 分析步骤 1 ...

  5. python实现京东商城

    用python实现简单版的京东商城 一.数据库准备 1. 商品表 create table goods(id int unsigned primary key auto_increment not n ...

  6. python爬京东联盟_python爬虫框架scrapy实战之爬取京东商城进阶篇

    前言 之前的一篇文章已经讲过怎样获取链接,怎样获得参数了,详情请看python爬取京东商城普通篇,本文将详细介绍利用python爬虫框架scrapy如何爬取京东商城,下面话不多说了,来看看详细的介绍吧 ...

  7. python爬虫爬取教程_python爬虫实战之爬取京东商城实例教程

    前言 本文主要介绍的是利用python爬取京东商城的方法,文中介绍的非常详细,下面话不多说了,来看看详细的介绍吧. 主要工具 scrapy BeautifulSoup requests 分析步骤 1. ...

  8. python模拟登录网站_Python爬虫实战之(四)| 模拟登录京东商城

    作者:xiaoyu 微信公众号:Python数据科学 知乎:Python数据分析师 前两篇和大家分享了爬虫中http的一些概念和使用方法,基础篇我们主要介绍了http的请求头,高级篇我们主要介绍了co ...

  9. Python抓取京东商城的所有笔记本电脑的参数

    最近洪爷要写数据挖掘的论文需要些数据,于是俺又有机会做苦力了.昨天刚刚回到学校,晚上就帮洪爷写了个爬虫来爬数据京东商城的笔记本的参数. 为了快速完成,基本原理就是人工找到笔记本的页面. 然后他有22页 ...

  10. 利用python爬虫爬取京东商城商品图片

    笔者曾经用python第三方库requests来爬取京东商城的商品页内容,经过解析之后发现只爬到了商品页一半的图片.(这篇文章我们以爬取智能手机图片为例) 当鼠标没有向下滑时,此时查看源代码的话,就会 ...

最新文章

  1. poj2602(高精度模拟加法)
  2. MySQL查看所有视图的命令
  3. 性能之巅:Linux网络性能分析工具-netstat,ifconfig,nicstat,traceroute,tcpdump
  4. 摩托罗拉能否追回逝去的那些年?
  5. ZOJ - 2676 Network Wars(01分数规划+最小割)
  6. Python中转换角度为弧度的radians()方法
  7. jsonp跨域原理_Rust 搭建可跨域访问服务器JsonP(一)
  8. Python编写俄罗斯方块小游戏
  9. 别小看无人配送,长大了就是自动驾驶的最终实现。
  10. 转载:一步一步和我学Apache JMeter
  11. python网络爬虫的特点_Python网络爬虫(一)- 入门基础
  12. srs部署到ubuntu 18.04 server
  13. mysql sql语句面试经典50题_常见的SQL面试题:经典50题(简单)
  14. 黑白群晖为Plex添加证书,开启HTTPS访问
  15. mencoder mencoder 安装使用及常用参数
  16. fireFox post请求插件,火狐浏览器插件
  17. 小麦苗的常用代码--常用命令(仅限自己使用)--上
  18. 【1401】机器翻译
  19. vant4的showtoast非正常显示问题
  20. xp无法搜索计算机,xp系统的笔记本电脑为什么搜不到手机热点的信号

热门文章

  1. WPF实现炫酷趋势图
  2. mysql5.6 relay.info_Relay log 导致复制启动失败
  3. 2019年前端大事件回顾:流年笑掷,未来可期
  4. android app 获得root 权限管理,Android获取超级管理员权限的实现
  5. 百度编辑器设置上传文件大小
  6. 大龄码农的新西兰移民之路
  7. Mybatis-Plus入门案例、以及为什么不建议使用MP?
  8. 神舟笔记本风扇声音很大怎么办
  9. 千帆竞发-Redis分布式锁
  10. mac上解决Resource temporarily unavailable