【python MySQL 笔记】python和MySQL交互、操作

【python MySQL 笔记】python和MySQL交互、操作

目录

1. 数据准备

2.  SQL演练

2.1 SQL语句强化练习

2.2. 将一个表拆为多个表

3. python操作MySQL

3.1. python操作MySQL的流程

3.2. 查询基本操作

3.3. 增删改基本操作

3.4. 参数化

思考


1. 数据准备

创建一个jing_dong库,库里创建一个goods表,并插入数据,用于SQL语句演练。

-- 创建 "京东" 数据库
create database jing_dong charset=utf8;

-- 使用 "京东" 数据库
use jing_dong;

-- 创建一个商品goods数据表
create table goods(
    id int unsigned primary key auto_increment not null,
    name varchar(150) not null,
    cate_name varchar(40) not null,
    brand_name varchar(40) not null,
    price decimal(10,3) not null default 0,
    is_show bit not null default 1,
    is_saleoff bit not null default 0
);


-- 向goods表中插入一些数据
insert into goods values(0,'r510vc 15.6英寸笔记本','笔记本','华硕','3399',default,default); 
insert into goods values(0,'y400n 14.0英寸笔记本电脑','笔记本','联想','4999',default,default);
insert into goods values(0,'g150th 15.6英寸游戏本','游戏本','雷神','8499',default,default); 
insert into goods values(0,'x550cc 15.6英寸笔记本','笔记本','华硕','2799',default,default); 
insert into goods values(0,'x240 超极本','超级本','联想','4880',default,default); 
insert into goods values(0,'u330p 13.3英寸超极本','超级本','联想','4299',default,default); 
insert into goods values(0,'svp13226scb 触控超极本','超级本','索尼','7999',default,default); 
insert into goods values(0,'ipad mini 7.9英寸平板电脑','平板电脑','苹果','1998',default,default);
insert into goods values(0,'ipad air 9.7英寸平板电脑','平板电脑','苹果','3388',default,default); 
insert into goods values(0,'ipad mini 配备 retina 显示屏','平板电脑','苹果','2788',default,default); 
insert into goods values(0,'ideacentre c340 20英寸一体电脑 ','台式机','联想','3499',default,default); 
insert into goods values(0,'vostro 3800-r1206 台式电脑','台式机','戴尔','2899',default,default); 
insert into goods values(0,'imac me086ch/a 21.5英寸一体电脑','台式机','苹果','9188',default,default); 
insert into goods values(0,'at7-7414lp 台式电脑 linux )','台式机','宏碁','3699',default,default); 
insert into goods values(0,'z220sff f4f06pa工作站','服务器/工作站','惠普','4288',default,default); 
insert into goods values(0,'poweredge ii服务器','服务器/工作站','戴尔','5388',default,default); 
insert into goods values(0,'mac pro专业级台式电脑','服务器/工作站','苹果','28888',default,default); 
insert into goods values(0,'hmz-t3w 头戴显示设备','笔记本配件','索尼','6999',default,default); 
insert into goods values(0,'商务双肩背包','笔记本配件','索尼','99',default,default); 
insert into goods values(0,'x3250 m4机架式服务器','服务器/工作站','ibm','6888',default,default); 
insert into goods values(0,'商务双肩背包','笔记本配件','索尼','99',default,default);

注:想以默认值插入时,若是主键,则0、null、default都可以。若是非主键,则只能用default

2.  SQL演练

2.1 SQL语句强化练习

基于以上数据表,进行一些语句的练习。

-- 查询类型cate_name为 '超极本' 的商品名称、价格
select name , price from goods where cate_name="超级本";
select name as 商品名称, price as 商品价格 from goods where cate_name="超级本";
+-----------------------------+--------------+
| 商品名称                    | 商品价格     |
+-----------------------------+--------------+
| x240 超极本                 |     4880.000 |
| u330p 13.3英寸超极本        |     4299.000 |
| svp13226scb 触控超极本      |     7999.000 |
+-----------------------------+--------------+

-- 显示商品的种类
select distinct cate_name from goods;
select cate_name from goods group by cate_name;
+---------------------+
| cate_name           |
+---------------------+
| 笔记本              |
| 游戏本              |
| 超级本              |
| 平板电脑            |
| 台式机              |
| 服务器/工作站       |
| 笔记本配件          |
+---------------------+

-- 显示商品种类中具体的商品的名称
select cate_name, group_concat(name) from goods group by cate_name;

-- 求所有电脑产品的平均价格,并且保留两位小数
select avg(price) from goods;
select round(avg(price),2) as avg_price from goods;
+---------------------+
| round(avg(price),2) |
+---------------------+
|             5570.57 |
+---------------------+

-- 显示每种类型商品的平均价格
select cate_name,avg(price) from goods group by cate_name;  -- 执行时先group by,再avg(price)

-- 查询每种类型的商品中 最贵、最便宜、平均价、数量
select cate_name,max(price),min(price),avg(price),count(*) from goods group by cate_name;

-- 查询所有价格大于平均价格的商品,并且按价格降序排序(注:子查询中先查出平均价格)
select id,name,price from goods 
where price > (select round(avg(price),2) as avg_price from goods) 
order by price desc;

-- 查询每种类型中最贵的价格
select cate_name , max(price) from goods group by cate_name;
-- 查询每种类型中最贵的电脑信息  (先把子查询结果当作一个表,再用连接查询,条件是连个表相应的字段信息相等)
select * from goods
inner join 
    (
        select
        cate_name, 
        max(price) as max_price, 
        min(price) as min_price, 
        avg(price) as avg_price, 
        count(*) from goods group by cate_name
    ) as goods_new_info 
on goods.cate_name=goods_new_info.cate_name and goods.price=goods_new_info.max_price;

-- 完善上一句查询,让同一种类型最高价的不止一个型号时,这些型号能显示在一起(用 order by)
select * from goods
inner join 
    (
        select
        cate_name, 
        max(price) as max_price, 
        min(price) as min_price, 
        avg(price) as avg_price, 
        count(*) from goods group by cate_name
    ) as goods_new_info 
on goods.cate_name=goods_new_info.cate_name and goods.price=goods_new_info.max_price order by goods_new_info.cate_name;

-- 查询每种类型中最贵的电脑的类型、名字和价格
select goods.cate_name,goods.name,goods.price from goods
inner join 
    (
        select
        cate_name, 
        max(price) as max_price, 
        min(price) as min_price, 
        avg(price) as avg_price, 
        count(*) from goods group by cate_name
    ) as goods_new_info 
on goods.cate_name=goods_new_info.cate_name and goods.price=goods_new_info.max_price order by goods_new_info.cate_name;
+---------------------+---------------------------------------+-----------+
| cate_name           | name                                  | price     |
+---------------------+---------------------------------------+-----------+
| 台式机              | imac me086ch/a 21.5英寸一体电脑       |  9188.000 |
| 平板电脑            | ipad air 9.7英寸平板电脑              |  3388.000 |
| 服务器/工作站       | mac pro专业级台式电脑                 | 28888.000 |
| 游戏本              | g150th 15.6英寸游戏本                 |  8499.000 |
| 笔记本              | y400n 14.0英寸笔记本电脑              |  4999.000 |
| 笔记本配件          | hmz-t3w 头戴显示设备                  |  6999.000 |
| 超级本              | svp13226scb 触控超极本                |  7999.000 |
+---------------------+---------------------------------------+-----------+

2.2. 将一个表拆为多个表

(注:实际中不会这样拆表,而是会先设计好数据表)

只有一个表 (goods表) 时,对数据的增删改查等管理是比较复杂,应该将一个大的表适当的进行拆分。

如:

将原来的一个表【goods】(id,name,cate_name,brand_name,price,is_show,is_saleoff)

拆为 商品分类表 【goods_cates 】(id, name ) 

商品品牌表 【goods_brands】(id, name)

........

对goods表进行更新、同步数据,如cate_name更新为cate_id, brand_name更新为 brand_id ...

创建 "商品分类" 表

创建商品分类表并插入数据:

-- 创建商品分类表
create table if not exists goods_cates(
    id int unsigned primary key auto_increment,
    name varchar(40) not null
);

-- 查询原goods表中商品的种类
select cate_name from goods group by cate_name;

-- 将goods表中分组查询的结果,即商品的种类写入到goods_cates数据表(把查询结果当作信息插入到goods_cates 表中,不用像一般插入一样写value)
insert into goods_cates (name) select cate_name from goods group by cate_name;

--查询goods_cates表
select * from goods_cates;
+----+---------------------+
| id | name                |
+----+---------------------+
|  1 | 台式机              |
|  2 | 平板电脑            |
|  3 | 服务器/工作站       |
|  4 | 游戏本              |
|  5 | 笔记本              |
|  6 | 笔记本配件          |
|  7 | 超级本              |
+----+---------------------+


数据同步

拆分出goods_cates表之后,对goods表进行更新、同步数据。通过goods_cates数据表来更新goods数据表。如字段cate_name的数据更新为对应的cate_id,并更新数据。

-- 通过goods_cates数据表来更新goods表
--(g.cate_name=c.name判断两个表对应的字段值相同时,更新goods表的cate_name数据为相应的id)
update goods as g ...... set g.cate_name=...
update goods as g inner join goods_cates as c on g.cate_name=c.name set g.cate_name=c.id;
-- 更新后,类别名放到了另一个表,cate_name更新为类别对应的id
+----+---------------------------------------+-----------+------------+-----------+---------+------------+
| id | name                                  | cate_name | brand_name | price     | is_show | is_saleoff |
+----+---------------------------------------+-----------+------------+-----------+---------+------------+
|  1 | r510vc 15.6英寸笔记本                 | 5         | 华硕       |  3399.000 |        |            |
|  2 | y400n 14.0英寸笔记本电脑              | 5         | 联想       |  4999.000 |        |            |
|  3 | g150th 15.6英寸游戏本                 | 4         | 雷神       |  8499.000 |        |            |
|  4 | x550cc 15.6英寸笔记本                 | 5         | 华硕       |  2799.000 |        |            |
|  5 | x240 超极本                           | 7         | 联想       |  4880.000 |        |            |
|  6 | u330p 13.3英寸超极本                  | 7         | 联想       |  4299.000 |        |            |
|  7 | svp13226scb 触控超极本                | 7         | 索尼       |  7999.000 |        |            |
|  8 | ipad mini 7.9英寸平板电脑             | 2         | 苹果       |  1998.000 |        |            |
|  9 | ipad air 9.7英寸平板电脑              | 2         | 苹果       |  3388.000 |        |            |
| 10 | ipad mini 配备 retina 显示屏          | 2         | 苹果       |  2788.000 |        |            |
| 11 | ideacentre c340 20英寸一体电脑        | 1         | 联想       |  3499.000 |        |            |
| 12 | vostro 3800-r1206 台式电脑            | 1         | 戴尔       |  2899.000 |        |            |
| 13 | imac me086ch/a 21.5英寸一体电脑       | 1         | 苹果       |  9188.000 |        |            |
| 14 | at7-7414lp 台式电脑 linux )          | 1         | 宏碁       |  3699.000 |        |            |
| 15 | z220sff f4f06pa工作站                 | 3         | 惠普       |  4288.000 |        |            |
| 16 | poweredge ii服务器                    | 3         | 戴尔       |  5388.000 |        |            |
| 17 | mac pro专业级台式电脑                 | 3         | 苹果       | 28888.000 |        |            |
| 18 | hmz-t3w 头戴显示设备                  | 6         | 索尼       |  6999.000 |        |            |
| 19 | 商务双肩背包                          | 6         | 索尼       |    99.000 |        |            |
| 20 | x3250 m4机架式服务器                  | 3         | ibm        |  6888.000 |        |            |
| 21 | 商务双肩背包                          | 6         | 索尼       |    99.000 |        |            |
+----+---------------------------------------+-----------+------------+-----------+---------+------------+

但是,此时如果通过 desc goods; 和 desc goods_cates; 就会发现虽然存的都是商品类型的id,但是 goods的cate_name Type为varchar,而 goods_cates 的id type为int(要修改表结构)。并且两个表没有关联,给goods的cate_name 插入值时,并不会通过goods_cates验证(要设置外键)。

通过alter table语句修改表结构

-- 改cate_name为 cate_id,并修改Type
alter table goods  
change cate_name cate_id int unsigned not null;


-- 语句:
alter table 表名
change ......;
change ......;

添加外键约束:对数据的有效性进行验证(关键字: foreign key)

alter table 表名1 add foreign key (字段1) references 表名2(字段2);  --给 表1 的 字段1 添加外键,引用的是 表2 的 字段2
alter table goods add foreign key (cate_id) references goods_cates(id);

注:添加外键时,要先删除无效数据

创建 "商品品牌表" 表

可以参考上面创建 "商品分类" 表,先创建表,再插入数据。

也可以通过create...select来创建数据表并且同时写入记录,一步到位

-- select brand_name from goods group by brand_name;

-- 在创建数据表的时候一起插入数据
-- 注意: 需要对brand_name 用as起别名,否则name字段就没有值(查到的字段要与插入的字段同名)
create table goods_brands (
    id int unsigned primary key auto_increment,
    name varchar(40) not null) select brand_name as name from goods group by brand_name;

-- 看一下结果
select * from goods_brands;
+----+--------+
| id | name   |
+----+--------+
|  1 | ibm    |
|  2 | 华硕   |
|  3 | 宏碁   |
|  4 | 惠普   |
|  5 | 戴尔   |
|  6 | 索尼   |
|  7 | 联想   |
|  8 | 苹果   |
|  9 | 雷神   |
+----+--------+

数据同步

通过goods_brands数据表来更新goods数据表

update goods as g inner join goods_brands as b on g.brand_name=b.name set g.brand_name=b.id;

通过alter table语句修改表结构

alter table goods  
change brand_name brand_id int unsigned not null;

添加外键约束:对数据的有效性进行验证(关键字: foreign key)

alter table 表名1 add foreign key (字段1) references 表名2(字段2);  --给 表1 的 字段1 添加外键,引用的是 表2 的 字段2
alter table goods add foreign key (brand_id) references goods_brands(id);

  • 如何在创建数据表的时候就设置外键约束呢?

  • 注意: goods 中的 cate_id 的类型一定要和 goods_cates 表中的 id 类型一致

create table goods(
    id int primary key auto_increment not null,
    name varchar(40) default '',
    price decimal(5,2),
    cate_id int unsigned,
    brand_id int unsigned,
    is_show bit default 1,
    is_saleoff bit default 0,
    foreign key(cate_id) references goods_cates(id),
    foreign key(brand_id) references goods_brands(id)
);
  • 如何取消外键约束
-- 需要先获取外键约束名称,该名称系统会自动生成,可以通过查看表创建语句来获取名称
show create table goods;
-- 获取名称之后就可以根据名称来删除外键约束
alter table goods drop foreign key 外键名称;

(查询外键名:show create table 表名;查询结果中CONSTRAINT后面的 既是外键名称)
  • 在实际开发中,很少会使用到外键约束,会极大的降低表更新的效率

3. python操作MySQL

3.1. python操作MySQL的流程

(1)ubuntu安装mysql软件

sudo apt-get install 软件名

(2)安装pymysql模块

  • 有网络时:pip3 install pymysql 或 sudo pip3 install pymysql 
  • 无网络时:下载好对应的 .whl 文件,在终端执行:pip install .whl 文件名 

(3)引入模块

在py文件中引入pymysql模块

import pymysql               # python3
from pymysql import *        # python3

import MySQLdb               # python2

(4)python操作MySQL的基本流程:

  • 创建connection对象
  • 创建游标cursor对象
  • 数据操作
  • 关闭connection对象、cursor对象

(5)connection对象和cursor对象介绍

Connection 对象:

  • 用于建立与数据库的连接

  • 创建对象:调用connect()方法

conn=connect(参数列表)
  • 参数host:连接的mysql主机,如果本机是'localhost'
  • 参数port:连接的mysql主机的端口,默认是3306
  • 参数database:数据库的名称
  • 参数user:连接的用户名
  • 参数password:连接的密码
  • 参数charset:通信采用的编码方式,推荐使用utf8

对象的方法

  • close()关闭连接
  • commit()提交
  • cursor()返回Cursor对象,用于执行sql语句并获得结果

Cursor对象:

  • 用于执行sql语句,使用频度最高的语句为select、insert、update、delete
  • 获取Cursor对象:调用Connection对象的cursor()方法
cs1=conn.cursor()

对象的方法

  • close()关闭
  • execute(operation [, parameters ])执行语句,返回受影响的行数,主要用于执行insert、update、delete语句,也可以执行create、alter、drop等语句
  • fetchone()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组
  • fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回(返回元祖的元祖
  • fetchmany(参数)执行查询语句时,获取结果集的指定行(通过参数指定),一行构成一个元组,再将这些元组装入一个元组返回

对象的属性

  • rowcount只读属性,表示最近一次execute()执行后受影响的行数
  • connection获得当前连接对象

 

3.2. 查询基本操作

查询数据

创建connection对象和游标cursor对象后,通过调用Cursor对象的execute来执行SQL语句, execute返回生效的(查出来的)行数。执行查询语句之后,通过 cursor对象.fetchone() 或 cursor对象.fetchmany(数量)(不写数量默认取一个) 或 cursor对象.fetchall() 取数据。(fetchone 返回元祖,fetchmany 和 fetchall 返回元祖的元祖)

from pymysql import *

def main():
    # 创建Connection连接(必须)
    conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
    # 获得Cursor对象(必须)
    cs1 = conn.cursor()

    # 执行select语句,并返回受影响的行数:查询一条数据 (通过调用Cursor对象的execute来执行SQL语句,execute返回生效的行数)
    count = cs1.execute('select id,name from goods where id>=4')
    # 打印受影响的行数
    print("查询到%d条数据:" % count)

    # 一行行的获取查询结果-----
    for i in range(count):
        # 获取查询的结果
        result = cs1.fetchone()
        # 打印查询的结果
        print(result)
        # 获取查询的结果

    # 一次获取查询结果的所有行----
    # result = cs1.fetchall()
    # print(result)
    

    # 关闭Cursor对象
    cs1.close()
    conn.close()

if __name__ == '__main__':
    main()

案例:京东商城 查询

用可选参数的形式,提供 1查询所有商品、2查询分类、 3查询品牌分类  的功能。

思路

  • 可用面向对象的方式,每个方法实现一种查询功能;
  • 数据库的连接和断开不用写在每个查询功能方法里,可在 __init__方法 连接、__del__方法 关闭连接。
  • 进一步,查询语句的实现也可作为一个方法供调用。
     
from pymysql import connect


class JD(object):
    def __init__(self):
        
        # 创建Connection连接
        self.conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
        # 获得Cursor对象
        self.cursor = self.conn.cursor()


    def __del__(self):
        
        # 关闭cursor对象
        self.cursor.close()   # 别漏了self.
        # 关闭Connection对象
        self.conn.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 * from goods;"
        self.execute_sql(sql)

    def show_cates(self):
        sql = "select name from goods_cates;"
        self.execute_sql(sql)

    def show_brands(self):
        sql = "select name from goods_brands;"
        self.execute_sql(sql)


    # 该方法不需要实例对象也不需要类对象,可以用静态方法实现
    @staticmethod
    def print_menu():
        print("-----京东------")
        print("1:所有的商品")
        print("2:所有的商品分类")
        print("3:所有的商品品牌分类")
        return input("请输入功能对应的序号:")
        
    def run(self):
        while True:
            num = self.print_menu()
            if num == "1":
                # 查询所有商品
                self.show_all_items()
            elif num == "2":
                # 查询分类
                self.show_cates()
            elif num == "3":
                # 查询品牌分类
                self.show_brands()
            else:
                print("输入有误,请重新输入...")


def main():
    # 1. 创建一个京东商城对象
    jd = JD()

    # 2. 调用这个对象的run方法,让其运行
    jd.run()


if __name__ == "__main__":
    main()

3.3. 增删改基本操作

  • 通过游标来处理增删改,通过连接对象来做commit。只有commit之后,增删改的语句才会生效;
  • 没commit之前,通过 连接对象.rollback() 可以取消一次execute;
  • 增删改都是对数据进行改动,在python中差异就是sql语句不同

案例:添加一个品牌分类(增)

from pymysql import connect


class JD(object):
    def __init__(self):
        
        # 创建Connection连接
        self.conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
        # 获得Cursor对象
        self.cursor = self.conn.cursor()

    def __del__(self):
        
        # 关闭cursor对象
        self.cursor.close()   # 别漏了self.
        # 关闭Connection对象
        self.conn.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 * from goods;"
        self.execute_sql(sql)

    def show_cates(self):
        sql = "select name from goods_cates;"
        self.execute_sql(sql)

    def show_brands(self):
        sql = "select name from goods_brands;"
        self.execute_sql(sql)

    def add_brands(self):
        item_name = input("输入新品牌的名字:")
        sql = '''insert into goods_brands (name) values("%s")''' % item_name  # 可用三引号防止引号冲突
        self.cursor.execute(sql)
        self.conn.commit()

    # 该方法不需要实例对象也不需要类对象,可以用静态方法实现
    @staticmethod
    def print_menu():
        print("-----京东------")
        print("1:所有的商品")
        print("2:所有的商品分类")
        print("3:所有的商品品牌分类")
        print("4:添加一个品牌分类")
        return input("请输入功能对应的序号:")
        
    def run(self):
        while True:
            num = self.print_menu()
            if num == "1":
                # 查询所有商品
                self.show_all_items()
            elif num == "2":
                # 查询分类
                self.show_cates()
            elif num == "3":
                # 查询品牌分类
                self.show_brands()
            elif num == "4":
                # 添加一个品牌分类
                self.add_brands()
            else:
                print("输入有误,请重新输入...")


def main():
    # 1. 创建一个京东商城对象
    jd = JD()

    # 2. 调用这个对象的run方法,让其运行
    jd.run()


if __name__ == "__main__":
    main()

3.4. 参数化

  • sql语句的参数化,可以有效防止sql注入
  • 注意:此处不同于python的字符串格式化,全部使用%s占位

在上一个案例中,添加功能 5 根据名字查询一个商品。

from pymysql import connect


class JD(object):
    def __init__(self):
        # 创建Connection连接
        self.conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
        # 获得Cursor对象
        self.cursor = self.conn.cursor()

    def __del__(self):
        # 关闭cursor对象
        self.cursor.close()   # 别漏了self.
        # 关闭Connection对象
        self.conn.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 * from goods;"
        self.execute_sql(sql)

    def show_cates(self):
        sql = "select name from goods_cates;"
        self.execute_sql(sql)

    def show_brands(self):
        sql = "select name from goods_brands;"
        self.execute_sql(sql)

    def add_brands(self):
        item_name = input("输入新品牌的名字:")
        sql = '''insert into goods_brands (name) values("%s")''' % item_name  # 用三引号防止引号冲突
        self.cursor.execute(sql)
        self.conn.commit()

    def get_info_by_name(self):
        find_name = input("请输入要查询的商品名字:")
	
        # # 非安全的方式
        # # 输入 ' or 1=1 or '   (引号也要输入) 就会被sql注入
        # sql="""select * from goods where name='%s';""" % find_name
        # print("------>%s<------" % sql)
        # self.execute_sql(sql)

        # 相对安全的方式
        # 构造参数列表
        sql = "select * from goods where name=%s"
        self.cursor.execute(sql, [find_name])	# [find_name]: 输入的值存到列表中
        print(self.cursor.fetchall())
        # 注意:
   	# 如果要是有多个参数,需要进行参数化
    	# 那么params = [数值1, 数值2....],此时sql语句中有多个%s即可
	
    # 该方法不需要实例对象也不需要类对象,可以用静态方法实现
    @staticmethod
    def print_menu():
        print("-----京东------")
        print("1:所有的商品")
        print("2:所有的商品分类")
        print("3:所有的商品品牌分类")
        print("4:添加一个品牌分类")
        print("5:根据名字查询一个商品")
        return input("请输入功能对应的序号:")
        
    def run(self):
        while True:
            num = self.print_menu()
            if num == "1":
                # 查询所有商品
                self.show_all_items()
            elif num == "2":
                # 查询分类
                self.show_cates()
            elif num == "3":
                # 查询品牌分类
                self.show_brands()
            elif num == "4":
                # 添加一个品牌分类
                self.add_brands()
            elif num == "5":
                # 根据名字查询商品
                self.get_info_by_name()
            else:
                print("输入有误,请重新输入...")


def main():
    # 1. 创建一个京东商城对象
    jd = JD()

    # 2. 调用这个对象的run方法,让其运行
    jd.run()


if __name__ == "__main__":
    main()

以上实例中,若查询的代码为:

find_name = input("请输入要查询的商品名字:")
sql="""select * from goods where name='%s';""" % find_name
print("------>%s<------" % sql)
  • 若用户输入为 'or 1=1 or '1  ,则整句sql语句就会是 : select * from goods where name=''or 1=1 or '1';  。其中1=1永远成立,就会形成sql注入,所有数据都没有安全性、会被查询到。
  • 安全的方式构造参数列表(看代码实现),利用execute来拼接sql语句字符串。
  • 本例只有一个参数,注意:如果要是有多个参数,需要进行参数化,那么params = [数值1, 数值2....],此时sql语句中有多个%s即可

思考

在以上数据库的基础上,添加顾客表【customer】(id, name, addr, tel)、订单表【orders】(......)、订单详情表【order_detail】(......) ;

在以上程序的基础上,添加注册、登录、下订单的功能。

创建 "顾客" 表

create table customer(
    id int unsigned auto_increment primary key not null,
    name varchar(30) not null,
    addr varchar(100),
    tel varchar(11) not null
);

创建 "订单" 表

create table orders(
    id int unsigned auto_increment primary key not null,
    order_date_time datetime not null,
    customer_id int unsigned,
    foreign key(customer_id) references customer(id)
);

创建 "订单详情" 表

create table order_detail(
    id int unsigned auto_increment primary key not null,
    order_id int unsigned not null,
    goods_id int unsigned not null,
    quantity tinyint unsigned not null,
    foreign key(order_id) references orders(id),
    foreign key(goods_id) references goods(id)
);

......

------end-------

发布了50 篇原创文章 · 获赞 10 · 访问量 6608

猜你喜欢

转载自blog.csdn.net/qq_23996069/article/details/104420591