【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 (selectcate_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 (selectcate_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 (selectcate_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 *        # python3import 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 connectclass 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)# 该方法不需要实例对象也不需要类对象,可以用静态方法实现@staticmethoddef 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 connectclass 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()# 该方法不需要实例对象也不需要类对象,可以用静态方法实现@staticmethoddef 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 connectclass 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即可# 该方法不需要实例对象也不需要类对象,可以用静态方法实现@staticmethoddef 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-------

【python MySQL 笔记】python和MySQL交互、操作相关推荐

  1. MySQL 笔记1 -- 安装MySQL及Navicat

    MySQL 笔记1 – 安装MySQL及Navicat MySQL 系列笔记是笔者学习.实践MySQL数据库的笔记 课程链接: MySQL 数据库基础入门教程 参考文档: MySQL 官方文档 一.安 ...

  2. (转载)[python学习笔记]Python语言程序设计(北理工 嵩天)

    作者:九命猫幺 博客出处:http://www.cnblogs.com/yongestcat/ 欢迎转载,转载请标明出处. 如果你觉得本文还不错,对你的学习带来了些许帮助,请帮忙点击右下角的推荐 阅读 ...

  3. Python学习笔记 - Python数据类型

    前言 在Python语言中,所有的数据类型都是类,每一个变量都是类的"实例".没有基本数据类型的概念,所以整数.浮点数和字符串也都是类. Python有6种标准数据类型:数字.字符 ...

  4. Python学习笔记 - Python语言概述和开发环境

    一.Python简介 1.1  Python语言简史 Python由荷兰人吉多·范罗苏姆(Guido van Rossum)于1989年圣诞节期间,在阿姆斯特丹,为了打发圣诞节的无聊时间,决心开发一门 ...

  5. 【狂神MySQL笔记】初识Mysql

    前端:页面:展示数据 后台:连接点:连接数据库,连接前端(控制,控制视图跳转,给前端传递数据) 数据库:存数据(txt,Excel,Word.....) 狂神说: 只会写代码->学好数据库(合格 ...

  6. 学python安装-Python学习笔记-Python安装

    Python安装 文章简介:本文介绍在不同操作系统中搭建Python编程环境. 一 搭建编程环境 在不同的操作系统中,Python存在细微的区别,下面介绍两个主要的Python版本. 1.1 Pyth ...

  7. Python学习笔记 - Python语法基础

    前言 本篇博文主要介绍Python中的一些最基础的语法,其中包括标识符.关键字.内置函数.变量.常量.表达式.语句.注释.模块和包等内容. 一.标识符.关键字和内置函数 任何一种语言都离不开标识符和关 ...

  8. Python学习笔记 Python概述 编码规范 输出与输入 变量 标识符

    Python学习第一天 Python的概述 1.Python的优缺点 1.1 优点: 1.2 缺点: 2.Python的编码规范 3.注释 3.Python的输出与输入 4.Python中的变量 5. ...

  9. Python学习笔记(7):操作Excel

    简述 Python对Excel操作的方法主要有openpyxl.xlsxwriter.xlrd.xlwt.xlutils这几种,下面我们逐个进行介绍. openpyxl openpyxl包提供了读写E ...

  10. Python与redis集群进行交互操作

    安装包如下 pip install redis-py-cluster redis-py-cluster源码地址https://github.com/Grokzen/redis-py-cluster 创 ...

最新文章

  1. 高亮提示、聚焦控件并滚动到浏览器中干好可以查看到该控件的位置
  2. django mysql save_python,django,向mysql更新数据时save()报错不能用
  3. DR模式 mysqlABB读写分离
  4. lookup无序查找_学习LOOKUP 函数实现无序查询
  5. Waveform Audio 驱动(Wavedev2)之:WAV API模拟
  6. Happy 牛 Year!牛年dotnet云原生技术趋势
  7. JavaScript(js)的replace问题的解决
  8. MySQL的timestamp字段可以使用的范围是多少
  9. LeetCode 669. 修剪二叉搜索树
  10. SLAM Cartographer(6)传感器桥梁
  11. 梯度下降法,最速下降法,牛顿法,Levenberg-Marquardt 修正,共轭方向法,共轭梯度法
  12. Cacti脚本及模板---PING
  13. 1060 Are They Equal (25 分)科学计数法,stl中string的各种函数用法
  14. 如何解决CAN FD与CAN网络共存问题
  15. 《Redis视频教程》(p1)
  16. 对于8086cpu的探索发现
  17. word一打字就有下划线_[word文档打字有下划线]下划线粗细不一致的原因:控制Word下划线与文字的距离...
  18. 聊聊数字姓氏:这个姓氏真占便宜,被称为最容易夺冠的姓氏!
  19. IMX6Q上蓝牙设备测试
  20. 哪个牌子的蓝牙耳机音质好?音质比较好的蓝牙耳机排名

热门文章

  1. 转换流StreamReader的使用介绍
  2. java实现空心验证码_Java实现验证码
  3. java iterable_Java基础之Iterable接口
  4. Vue.js 最新官方下载地址与项目导入
  5. JS中的Ajax发送请求获取数据流程
  6. 小学生课间必备游戏(三子棋)
  7. 工业相机接口标准详解
  8. STC12C5A60S2_DHT11驱动
  9. c语言中dfs算法不定起点问题,dfs算法(dfs算法例子)
  10. Iris: 比ScanContext更加精确高效的激光回环检测方法(IROS 2020)