iis服务器助手广告广告
返回顶部
首页 > 资讯 > 数据库 >MySQL和Python交互的示例
  • 674
分享到

MySQL和Python交互的示例

pythonmysql 2022-05-18 12:05:15 674人浏览 八月长安
摘要

一.准备数据 创建数据表 -- 创建 "京东" 数据库 create database jing_dong charset=utf8; -- 使用 "京东" 数据库 use jing_dong; -- 创建

一.准备数据

创建数据表


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

二.sql演练

1. SQL语句的强化

查询类型cate_name为 '超极本' 的商品名称、价格


select name,price from goods where cate_name = '超级本';

显示商品的种类


select cate_name from goods group by cate_name;

求所有电脑产品的平均价格,并且保留两位小数


select round(avg(price),2) as avg_price from goods;

显示每种商品的平均价格


select cate_name,avg(price) from goods group by cate_name;

查询每种类型的商品中 最贵、最便宜、平均价、数量


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

2. 创建 "商品分类"" 表


-- 创建商品分类表
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_cates数据表


insert into goods_cates (name) select cate_name from goods group by cate_name;

3. 同步表数据

通过goods_cates数据表来更新goods表


update goods as g inner join goods_cates as c on g.cate_name=c.name set g.cate_name=c.id;

4. 创建 "商品品牌表" 表

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

5. 同步数据

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

6. 修改表结构

查看 goods 的数据表结构,会发现 cate_name 和 brand_name对应的类型为 varchar 但是存储的都是数字


desc goods;

通过alter table语句修改表结构


alter table goods 
change cate_name cate_id int unsigned not null,
change brand_name brand_id int unsigned not null;

7. 外键

分别在 goods_cates 和 goods_brands表中插入记录


insert into goods_cates(name) values ('路由器'),('交换机'),('网卡');
insert into goods_brands(name) values ('海尔'),('清华同方'),('神舟');

在 goods 数据表中写入任意记录


insert into goods (name,cate_id,brand_id,price)
values('LaserJet Pro P1606dn 黑白激光打印机', 12, 4,'1849');

查询所有商品的详细信息 (通过内连接)


select g.id,g.name,c.name,b.name,g.price from goods as g
inner join goods_cates as c on g.cate_id=c.id
inner join goods_brands as b on g.brand_id=b.id;

查询所有商品的详细信息 (通过左连接)


select g.id,g.name,c.name,b.name,g.price from goods as g
left join goods_cates as c on g.cate_id=c.id
left join goods_brands as b on g.brand_id=b.id;
  • 如何防止无效信息的插入,就是可以在插入前判断类型或者品牌名称是否存在呢? 可以使用之前讲过的外键来解决
  • 外键约束:对数据的有效性进行验证
  • 关键字: foreign key,只有 innodb数据库引擎 支持外键约束
  • 对于已经存在的数据表 如何更新外键约束

-- 给brand_id 添加外键约束成功
alter table goods add foreign key (brand_id) references goods_brands(id);
-- 给cate_id 添加外键失败
-- 会出现1452错误
-- 错误原因:已经添加了一个不存在的cate_id值12,因此需要先删除
alter table goods add foreign key (cate_id) references goods_cates(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 外键名称;

在实际开发中,很少会使用到外键约束,会极大的降低表更新的效率

三.数据库的设计

创建 "商品分类" 表(之前已经创建,无需再次创建)


create table goods_cates(
 id int unsigned primary key auto_increment not null,
 name varchar(40) not null
);

创建 "商品品牌" 表(之前已经创建,无需再次创建)


create table goods_brands (
 id int unsigned primary key auto_increment not null,
 name varchar(40) not null
);

创建 "商品" 表(之前已经创建,无需再次创建)


create table goods(
 id int unsigned 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)
);

创建 "顾客" 表


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

说明

  • 以上创建表的顺序是有要求的,即如果goods表中的外键约束用的是goods_cates或者是goods_brands,那么就应该先创建这2个表,否则创建goods会失败
  • 创建外键时,一定要注意类型要相同,否则失败

四.python 中操作 Mysql 步骤

引入模块

在py文件中引入pymysql模块


from pymysql import *

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()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回

对象的属性

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

五.增删改查


from pymysql import *

def main():
 # 创建Connection连接
 conn = connect(host='localhost',port=3306,database='jing_dong',user='root',password='mysql',charset='utf8')
 # 获得Cursor对象
 cs1 = conn.cursor()
 # 执行insert语句,并返回受影响的行数:添加一条数据
 # 增加
 count = cs1.execute('insert into goods_cates(name) values("硬盘")')
 #打印受影响的行数
 print(count)

 count = cs1.execute('insert into goods_cates(name) values("光盘")')
 print(count)

 # # 更新
 # count = cs1.execute('update goods_cates set name="机械硬盘" where name="硬盘"')
 # # 删除
 # count = cs1.execute('delete from goods_cates where id=6')

 # 提交之前的操作,如果之前已经之执行过多次的execute,那么就都进行提交
 conn.commit()

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

if __name__ == '__main__':
 main()

查询一行数据


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语句,并返回受影响的行数:查询一条数据
 count = cs1.execute('select id,name from goods where id>=4')
 # 打印受影响的行数
 print("查询到%d条数据:" % count)

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

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

if __name__ == '__main__':
 main()

查询多行数据


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语句,并返回受影响的行数:查询一条数据
 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()

六.参数化

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

from pymysql import *

def main():

 find_name = input("请输入物品名称:")

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


 # # 非安全的方式
 # # 输入 " or 1=1 or " (双引号也要输入)
 # sql = 'select * from goods where name="%s"' % find_name
 # print("""sql===>%s<====""" % sql)
 # # 执行select语句,并返回受影响的行数:查询所有数据
 # count = cs1.execute(sql)

 # 安全的方式
 # 构造参数列表
 params = [find_name]
 # 执行select语句,并返回受影响的行数:查询所有数据
 count = cs1.execute('select * from goods where name=%s', params)
 # 注意:
 # 如果要是有多个参数,需要进行参数化
 # 那么params = [数值1, 数值2....],此时sql语句中有多个%s即可 

 # 打印受影响的行数
 print(count)
 # 获取查询的结果
 # result = cs1.fetchone()
 result = cs1.fetchall()
 # 打印查询的结果
 print(result)
 # 关闭Cursor对象
 cs1.close()
 # 关闭Connection对象
 conn.close()

if __name__ == '__main__':
 main()

以上就是MySQL和Python交互的示例的详细内容,更多关于MySQL和python交互的资料请关注自学编程网其它相关文章!

您可能感兴趣的文档:

--结束END--

本文标题: MySQL和Python交互的示例

本文链接: https://www.lsjlt.com/news/10188.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python实现MySql数据库交互的示例
    目录一、使用mysql进行持久化存储二、安装MySql数据库和python库PyMySQL三、使用pymysql链接mysql数据库四、创建表五、插入数据六、后记一、使用MySql进行持久化存储 在任何应用中,都需要持久...
    99+
    2023-01-06
    PythonMySql数据库交互 PythonMySql交互
  • Flex和Html交互的示例分析
    这篇文章给大家分享的是有关Flex和Html交互的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。Flex和Html交互◆Flex和Html交互之Flex嵌入到Html:用swfobject,下载的.js地...
    99+
    2023-06-17
  • MySQL和Python怎么交互
    本篇内容主要讲解“MySQL和Python怎么交互”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“MySQL和Python怎么交互”吧!一.准备数据创建数据表-- 创建 &qu...
    99+
    2023-06-07
  • JavaScript与CSS和Sass的交互示例
    这篇“JavaScript与CSS和Sass的交互示例”除了程序员外大部分人都不太理解,今天小编为了让大家更加理解“JavaScript与CSS和Sass的交互示例”,给大家总结了以下内容,具有一定借鉴价值,内容详细步骤清晰,细节处理妥当,...
    99+
    2023-06-06
  • python 管理系统实现mysql交互的示例代码
    没配置的可以看一下我上一篇 地址 开启小皮 数据库text 数据库表 student 字段 student_no name age sex 效果图如下 增 删 查 改 ...
    99+
    2024-04-02
  • Android和PHP MYSQL交互开发实例
    目录总述1.安卓客户端2.服务器端3.MYSQL数据库4.总结总述 简单的说,安卓客户端通过Http向本地服务器发出请求,访问指定的php代码,服务器端通过php代码执行数据库的操作...
    99+
    2024-04-02
  • Android中js和原生交互的示例代码
    本文介绍了Android中js和原生交互的示例代码,分享给大家,具体如下:加载webview的类public class MainActivity extends Activity { @Override protected void ...
    99+
    2023-05-30
    android js 交互
  • laravel使用workerman用户交互、服务器交互的示例分析
                               laravel使用workerman 用户交...
    99+
    2023-06-14
  • Angular中组件交互的示例分析
    这篇文章将为大家详细讲解有关Angular中组件交互的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。Angular 组件交互组件交互: 组件通讯,让两个或多个组件之间共享信息。使用场景: 当某个功...
    99+
    2023-06-14
  • Angular2中组件交互的示例分析
    这篇文章主要为大家展示了“Angular2中组件交互的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Angular2中组件交互的示例分析”这篇文章吧。1...
    99+
    2024-04-02
  • python编程matplotlib交互绘制Julia集示例解析
    目录Julia集matplotlib绑定事件缩放所谓Julia集就是类似下面的美妙的图案 Julia集 特别地,当 c = z的初始值时,符合收敛条件的 z 的便构成大名鼎鼎的M...
    99+
    2024-04-02
  • python实现与Oracle数据库交互操作示例
    目录1、安装准备2、instantclient的安装说明3、instantclient安装步骤4、还有几个需要注意的地方1)设置NLS_LANG环境变量:解决中文乱码2)关于TNS_...
    99+
    2024-04-02
  • python与mysql交互中的各种坑
    开始学python 交互MySQLdb,踩了很多坑 第一个 %d format: a number is required, not str 参照以下博客: https://blog.csdn.net/u011878172/article...
    99+
    2023-01-30
    python mysql
  • 前端ajax与后端交互的示例分析
    这篇文章主要介绍了前端ajax与后端交互的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。前端中常常用的与后端交换数据的话,通常是要用...
    99+
    2024-04-02
  • python编写第一个交互程序步骤示例教程
    Input()函数编写 1.编写一个稍微复杂一点的程序。使用Input()函数编写一个请用户输入名字的程序。 (1)打开IDLE开发环境,然后选择“File”...
    99+
    2024-04-02
  • Vue前后端数据交互与显示的示例分析
    小编给大家分享一下Vue前后端数据交互与显示的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!一、技术概述将后端所计算的数据呈现在前端页面的相应位置并根据用...
    99+
    2023-06-15
  • PHP与JavaScript下Cookie交互使用的示例分析
    小编给大家分享一下PHP与JavaScript下Cookie交互使用的示例分析,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!PHP与JavaScript下Cookie的交互使用下面的例子列出几种情形交互场景,列出JS和ph...
    99+
    2023-06-15
  • linux自动化交互脚本expect的示例分析
    这篇文章将为大家详细讲解有关linux自动化交互脚本expect的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。什么是Linux系统Linux是一种免费使用和自由传播的类UNIX操作系统,是一个基...
    99+
    2023-06-09
  • python怎么与mysql数据库交互
    本篇内容介绍了“python怎么与mysql数据库交互”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!  1、安装pymysql库  如果你想...
    99+
    2023-06-02
  • Servlet3.0与纯javascript通过Ajax交互的示例分析
    这篇文章主要介绍Servlet3.0与纯javascript通过Ajax交互的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!虽然js.html是一个纯静态的页面,但是以下的程...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作