[Notes] python python MySQL and MySQL interactive operation

[Notes] python python MySQL and MySQL interactive operation

table of Contents

1. Data Preparation

2. SQL Walkthrough

2.1 SQL statement strengthening exercises

2.2 The table split in a plurality of tables

3. python MySQL operation

3.1. Python MySQL operation process

3.2. The basic query operations

3.3. Basic CRUD operations

3.4. Parameterization

Think


1. Data Preparation

Create a jing_dong library, library create a goods table, and insert the data for SQL statements drills.

-- 创建 "京东" 数据库
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);

Note: want to insert a default value when, if the primary key, 0, null, default can be . If the non-primary key, you can only use default .

 

2. SQL Walkthrough

 

2.1 SQL statement strengthening exercises

Based on the above data table, to practice some of the statements.

-- 查询类型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 The table split in a plurality of tables

(Note: this does not actually split the table, but will first design a good data table)

Is only one table (table Goods), additions and deletions to change search data management is complicated and the like, should be a large table of the appropriate split.

Such as:

The original table [goods] (id, name, cate_name, brand_name, price, is_show, is_saleoff)

Split for the classification of goods [goods_cates] (id, name) 

Brand goods_brands table [] (id, name)

........

Of the goods table updates, synchronization data, such as updated cate_name cate_id, brand_name updated brand_id ...

 

Create "Categories" list

Categories create tables and insert data:

-- 创建商品分类表
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 | 超级本              |
+----+---------------------+


 

data synchronization

After splitting the goods_cates table, the table is updated on the goods, synchronization data. Goods data table is updated by the data table goods_cates. The updated data fields cate_name corresponding cate_id, and updates the data.

-- 通过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 |        |            |
+----+---------------------------------------+-----------+------------+-----------+---------+------------+

However, if by this time desc goods; will find that although the types of goods are stored id, but the goods is cate_name Type varchar, and goods_cates is the id type int (to; and desc goods_cates modified table structure ). And the two tables is not associated, when goods of value to cate_name inserted, and does not verify (through goods_cates foreign key ).

Modified table structure alter table statement by

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


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

Add foreign key constraint: to verify the validity of data (keyword: 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);

Note: When you add a foreign key, first remove the invalid data

 

Create a "Brand list" table

You can create refer to the above "Categories" list, first create table, then insert the data.

You can also create a data table by create ... select and write records at the same time, in one step

-- 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 | 雷神   |
+----+--------+

data synchronization

Goods data table is updated by the data table goods_brands

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

Modified table structure alter table statement by

alter table goods  
change brand_name brand_id int unsigned not null;

Add foreign key constraint: to verify the validity of data (keyword: 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);

Attached :

  • How do you set up a foreign key constraint when creating the data table?

  • Note: goods of the type cate_id must be goods_cates table id and the type of agreement

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)
);
  • How to cancel the foreign key constraint
-- 需要先获取外键约束名称,该名称系统会自动生成,可以通过查看表创建语句来获取名称
show create table goods;
-- 获取名称之后就可以根据名称来删除外键约束
alter table goods drop foreign key 外键名称;

(查询外键名:show create table 表名;查询结果中CONSTRAINT后面的 既是外键名称)
  • In the actual development, rarely using foreign key constraint, will greatly reduce the efficiency of table updates

 

 

3. python MySQL operation

 

3.1. Python MySQL operation process

 

(1) ubuntu install mysql software

sudo apt-get install the software name

 

(2) Installation module pymysql

  • When available: PIP3 install pymysql  or  sudo pip3 install pymysql 
  • When no network: Download good .whl corresponding file, in a terminal execute: PIP install .whl file name 

 

(3) into the module

Introduced pymysql module py files

import pymysql               # python3
from pymysql import *        # python3

import MySQLdb               # python2

 

(4) basic flow of python MySQL operation:

  • Create a connection object
  • Create a cursor cursor objects
  • Data Manipulation
  • Close connection objects, cursor objects

 

(5) connection object and the cursor object Introduction

Connection object:

  • For establishing a connection with the database

  • Create Object: call connect () method

conn=connect(参数列表)
  • Parameters host: mysql host connection, if the unit is 'localhost'
  • Parameters port: Port mysql host connections, default is 3306
  • Name of the database: parameter database
  • Parameters user: username connections
  • Parameters password: password connection
  • Parameters charset: encoding communications using recommended utf8

Methods of objects

  • close () Closes connection
  • commit () submitted
  • cursor () returns Cursor object for executing sql statement and get the results

 

Cursor object:

  • For executing sql statements, statements highest frequency of use to select, insert, update, delete
  • Gets Cursor object: to call the Connection object's cursor () method
cs1=conn.cursor()

Methods of objects

  • close () Closes
  • execute (operation [, parameters]) the statement is executed, returns the number of rows affected, mainly for performing insert, update, delete statements may be executed create, alter, drop such phrases
  • either fetchone () case of a query, the query result set acquiring a first data row, returns a tuple
  • or fetchall () is executed query, the result set acquired all the rows, a line composed of a tuple, then these elements is assembled into a tuple returned ( return Ganso tuples )
  • fetchmany (parameter) is executed query, obtain the specified row of the result set (specified by parameters), constitute a tuple row, and then assembling these elements into a tuple returns

Properties of the object

  • rowcount read-only attribute of the last execute () the number of rows affected after execution
  • connection to get the current connection object

 

3.2. The basic query operations

Query data

After creating the connection object and the cursor cursor object, to execute a SQL statement calls Cursor object of the Execute , the Execute returns the number of rows (check out) came into force. After executing a query, by cursor object .fetchone ()  or  cursor object .fetchmany (number) (not written to take a number of default) or  cursor object .fetchall ()  to take data. (Either fetchone returned tuples, fetchmany fetchall and return neuron progenitor Ganso)

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()

 

 

Case : Jingdong Mall query

In the form of optional parameters, providing a query for all commodities, query classification 2, 3 queries brand classification.

Ideas :

  • An object oriented manner, each method to implement a query function;
  • Database connection and disconnection without written in each query function method, can be connected in the __init__ method, __ del__ method to close the connection.
  • Further, to achieve the query can also be used as a method for the call.
     
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. Basic CRUD operations

  • By cursor processed additions and deletions by the connection object do commit. Only after commit, additions and deletions to the sentence to take effect;
  • Before did not commit, can be canceled once execute by connecting objects .rollback ();
  • Additions and deletions are changes to the data, the difference in python is different sql statement

Case : Adding a Brand (increase)

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. Parameterization

  • Parametric sql statement, can effectively prevent sql injection
  • Note: Unlike string formatting python herein, all the% s placeholder

In one case, to add functionality to query a 5 merchandise by name.

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()

The above example, if the code query is:

find_name = input("请输入要查询的商品名字:")
sql="""select * from goods where name='%s';""" % find_name
print("------>%s<------" % sql)
  • If the user input  'or =. 1. 1 or'. 1   , the sentence sql statement would be:  SELECT * WHERE from Goods name = '' or =. 1. 1 or '. 1';   . Where 1 = 1 is always set up, it will form a sql injection, all the data is no security, will be queried.
  • Safe way to construct the argument list (see code implementation), use to execute splicing sql statement string.
  • The present embodiment is only one parameter, NOTE: If there was a plurality of parameters, parameterization is required, then params = [value 1, value 2 ....], when a plurality of the sql statement to% s .

 

Think

On the basis of the above database, add the customer table [customer] (id, name, addr, tel), order form [orders] (......), [Order Details table order_detail] (...... );

Based on the above program, the add register, login, place an order function.

Create a "customer" table

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
);

Creating the "Orders" table

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)
);

Creating "Order Details" table

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-------

Published 50 original articles · won praise 10 · views 6608

Guess you like

Origin blog.csdn.net/qq_23996069/article/details/104420591