python中操作mysql的pymysql模块详解
来源:SegmentFault
2023-02-24 21:33:15
0浏览
收藏
有志者,事竟成!如果你在学习数据库,那么本文《python中操作mysql的pymysql模块详解》,就很适合你!文章讲解的知识点主要包括MySQL、python、pymysql,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~
简述
pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。但目前pymysql支持python3.x而后者不支持3.x版本。
本文测试python版本:3.5.2。mysql版本:5.7.18
一、安装
pip install pymysql
二、使用操作
1. 执行SQL
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'junxi'
import pymysql
# 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='blog', passwd='123456', db='blog', charset='utf8')
# 创建游标, 查询数据默认为元组类型
cursor = conn.cursor()
# 执行SQL,并返回收影响行数
row1 = cursor.execute("update users set password = '123'")
print(row1)
# 执行SQL,并返回受影响行数
row2 = cursor.execute("update users set password = '456' where id > %s", (1,))
print(row2)
# 执行SQL,并返回受影响行数(使用pymysql的参数化语句防止SQL注入)
row3 = cursor.executemany("insert into users(username, password, email)values(%s, %s, %s)", [("ceshi3", '333', 'ceshi3@11.com'), ("ceshi4", '444', 'ceshi4@qq.com')])
print(row3)
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
提示:存在中文的时候,连接需要添加charset='utf8',否则中文显示乱码。
2、获取查询数据
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'junxi'
import pymysql
# 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='blog', passwd='123456', db='blog', charset='utf8')
# 创建游标, 查询数据默认为元组类型
cursor = conn.cursor()
cursor.execute("select * from users")
# 获取第一行数据
row_1 = cursor.fetchone()
print(row_1)
# 获取前n行数据
row_n = cursor.fetchmany(3)
print(row_n)
# 获取所有数据
row_3 = cursor.fetchall()
print(row_3)
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
3、获取新创建数据自增ID
可以获取到最新自增的ID,也就是最后插入的一条数据ID
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'junxi'
import pymysql
# 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='blog', passwd='123456', db='blog', charset='utf8')
# 创建游标, 查询数据默认为元组类型
cursor = conn.cursor()
cursor.executemany("insert into users(username, password, email)values(%s, %s, %s)", [("ceshi3", '333', 'ceshi3@11.com'), ("ceshi4", '444', 'ceshi4@qq.com')])
new_id = cursor.lastrowid
print(new_id)
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
4、移动游标
操作都是靠游标,那对游标的控制也是必须的
注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如: cursor.scroll(1,mode='relative') # 相对当前位置移动 cursor.scroll(2,mode='absolute') # 相对绝对位置移动
5、fetch数据类型
关于默认获取的数据是元组类型,如果想要或者字典类型的数据,即:
import pymysql
# 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='blog', passwd='123456', db='blog', charset='utf8')
# 游标设置为字典类型
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 左连接查询
r = cursor.execute("select * from users as u left join articles as a on u.id = a.user_id where a.user_id = 2")
result = cursor.fetchall()
print(result)
# 查询一个表的所有字段名
c = cursor.execute("SHOW FULL COLUMNS FROM users FROM blog")
cc = cursor.fetchall()
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
查看运行结果:
[{'user_id': 2, 'id': 2, 'password': '456', 'email': 'xinlei2017@test.com', 'a.id': 2, 'content': '成名之路', 'title': '星光大道', 'username': 'tangtang'}]
6、调用存储过程
a、调用无参存储过程
#! /usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='blog', passwd='123456', db='blog', charset='utf8')
#游标设置为字典类型
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#无参数存储过程
cursor.callproc('p2') #等价于cursor.execute("call p2()")
row_1 = cursor.fetchone()
print row_1
conn.commit()
cursor.close()
conn.close()
b、调用有参存储过程
#! /usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='blog', passwd='123456', db='blog', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.callproc('p1', args=(1, 22, 3, 4))
#获取执行完存储的参数,参数@开头
cursor.execute("select @p1,@_p1_1,@_p1_2,@_p1_3")
# {u'@_p1_1': 22, u'@p1': None, u'@_p1_2': 103, u'@_p1_3': 24}
row_1 = cursor.fetchone()
print row_1
conn.commit()
cursor.close()
conn.close()
三、关于pymysql防注入
1、字符串拼接查询,造成注入
正常查询语句:
#! /usr/bin/env python # -*- coding:utf-8 -*- import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306, user='blog', passwd='123456', db='blog', charset='utf8') cursor = conn.cursor() username = "ceshi1" password = "ceshi1passwd" # 正常构造语句的情况 sql = "select username, password from users where user='%s' and pass='%s'" % (username, password) # sql = select username, password from users where user='ceshi1' and pass='ceshi1passwd' row_count = cursor.execute(sql) row_1 = cursor.fetchone() print row_count, row_1 conn.commit() cursor.close() conn.close()
构造注入语句:
#! /usr/bin/env python # -*- coding:utf-8 -*- import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306, user='blog', passwd='123456', db='blog', charset='utf8') cursor = conn.cursor() username = "u1' or '1'-- " password = "u1pass" sql="select username, password from users where username='%s' and password='%s'" % (username, password) # 拼接语句被构造成下面这样,永真条件,此时就注入成功了。因此要避免这种情况需使用pymysql提供的参数化查询。 # select user,pass from tb7 where user='u1' or '1'-- ' and pass='u1pass' row_count = cursor.execute(sql) row_1 = cursor.fetchone() print row_count,row_1 conn.commit() cursor.close() conn.close()
2、避免注入,使用pymysql提供的参数化语句
正常参数化查询
#! /usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='blog', passwd='123456', db='blog', charset='utf8')
cursor = conn.cursor()
username="u1"
password="u1pass"
#执行参数化查询
row_count=cursor.execute("select username,password from tb7 where username=%s and password=%s",(username,password))
row_1 = cursor.fetchone()
print row_count,row_1
conn.commit()
cursor.close()
conn.close()
构造注入,参数化查询注入失败。
#! /usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='blog', passwd='123456', db='blog', charset='utf8')
cursor = conn.cursor()
username="u1' or '1'-- "
password="u1pass"
#执行参数化查询
row_count=cursor.execute("select username,password from users where username=%s and password=%s",(username,password))
#内部执行参数化生成的SQL语句,对特殊字符进行了加\转义,避免注入语句生成。
# sql=cursor.mogrify("select username,password from users where username=%s and password=%s",(username,password))
# print sql
#select username,password from users where username='u1\' or \'1\'-- ' and password='u1pass'被转义的语句。
row_1 = cursor.fetchone()
print row_count,row_1
conn.commit()
cursor.close()
conn.close()
结论:excute执行SQL语句的时候,必须使用参数化的方式,否则必然产生SQL注入漏洞。
3、使用存mysql储过程动态执行SQL防注入
使用MYSQL存储过程自动提供防注入,动态传入SQL到存储过程执行语句。
delimiter \\
DROP PROCEDURE IF EXISTS proc_sql \\
CREATE PROCEDURE proc_sql (
in nid1 INT,
in nid2 INT,
in callsql VARCHAR(255)
)
BEGIN
set @nid1 = nid1;
set @nid2 = nid2;
set @callsql = callsql;
PREPARE myprod FROM @callsql;
-- PREPARE prod FROM 'select * from users where nid>? and nid'; 传入的值为字符串,?为占位符
-- 用@p1,和@p2填充占位符
EXECUTE myprod USING @nid1,@nid2;
DEALLOCATE prepare myprod;
END\\
delimiter ;
set @nid1=12;
set @nid2=15;
set @callsql = 'select * from users where nid>? and nid';
CALL proc_sql(@nid1,@nid2,@callsql)
pymsql中调用
#! /usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='blog', passwd='123456', db='blog', charset='utf8')
cursor = conn.cursor()
sql1="select * from users where nid>? and nid"
cursor.callproc('proc_sql', args=(11, 15, sql1))
rows = cursor.fetchall()
print rows
conn.commit()
cursor.close()
conn.close()
四、使用with简化连接过程
# 使用with简化连接过程,每次都连接关闭很麻烦,使用上下文管理,简化连接过程
import pymysql
import contextlib
# 定义上下文管理器,连接后自动关闭连接
@contextlib.contextmanager
def mysql(host='127.0.0.1', port=3306, user='blog', passwd='123456', db='blog', charset='utf8'):
conn = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db, charset=charset)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
try:
yield cursor
finally:
conn.commit()
cursor.close()
conn.close()
# 执行sql
with mysql() as cursor:
# 左连接查询
r = cursor.execute("select * from users as u left join articles as a on u.id = a.user_id where a.user_id = 2")
result = cursor.fetchall()
print(result)
查看运行结果:
[{'title': '星光大道', 'username': 'tangtang', 'user_id': 2, 'email': 'xinlei3166@126.com', 'a.id': 2, 'content': '成名之路', 'password': '456', 'id': 2}]以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于数据库的相关知识,也可关注golang学习网公众号。
版本声明
本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
无需加配!1核1G小服务器也能跑mysql8.0
- 上一篇
- 无需加配!1核1G小服务器也能跑mysql8.0
- 下一篇
- PHP脚本导出MySQL数据字典
查看更多
最新文章
-
- 数据库 · MySQL | 2小时前 |
- MySQL invisible index 如何安全观察索引下线影响
- 300浏览 收藏
-
- 数据库 · MySQL | 3小时前 | MySQL · 索引优化 · generated column · mysql 索引 优化器 生成列
- MySQL 生成列索引为什么没有被优化器使用
- 300浏览 收藏
-
- 数据库 · MySQL | 6小时前 |
- MySQL 窗口函数取每组最新记录时如何处理并列时间
- 242浏览 收藏
-
- 数据库 · MySQL | 7小时前 |
- MySQL JSON_VALUE 返回 NULL 时怎么区分缺少路径和空值
- 170浏览 收藏
-
- 数据库 · MySQL | 9小时前 | MySQL · JSON查询 · JSON_TABLE · SQL技巧 · mysql JSON_TABLE FOR ORDINALITY JSON数组序号
- MySQL JSON_TABLE 的 FOR ORDINALITY 怎么保留数组原始序号
- 139浏览 收藏
-
- 数据库 · MySQL | 11小时前 |
- MySQL 复制延迟升高时怎么区分 SQL 线程和 IO 线程
- 304浏览 收藏
-
- 数据库 · MySQL | 13小时前 | MySQL事件 · 事件调度器 · 任务表排查 · mysql 定时任务 CREATE EVENT Event Scheduler INFORMATION_SCHEMA.EVENTS
- MySQL 事件调度器执行了但任务表没有更新怎么排查
- 486浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 47次使用
-
- SuperCLUE
- SuperCLUE是权威的中文大语言模型综合评测基准,涵盖语言理解、知识应用、AI Agent智能体及安全性等12项核心能力。通过多轮对话与客观测试,定期发布榜单与技术报告,为模型研发、优化及行业选型提供科学依据。
- 198次使用
-
- C-Eval
- 深入了解C-Eval中文评估套件,涵盖52个学科与4级难度。本文详解其功能特点、Zero-shot/Few-shot使用方法及代码示例,助您全面评测LLM中文理解与泛化能力。
- 133次使用
-
- AI Prompt Library
- 探索AI Prompt Library免费资源库,涵盖营销、写作及多场景AI提示词。兼容ChatGPT、Claude等工具,一键复制优化输出,提升工作效率。
- 67次使用
-
- Generrated
- Generrated汇集9300+张DALL·E生成图像及对应提示词,支持查看完整图集、对比DALL·E 2与3版本差异,是AI绘图新手学习Prompt设计与获取创作灵感的实用工具。
- 47次使用
查看更多
相关文章
-
- MySQL 明明加了索引,为什么查询还是很慢?先查这 6 个点
- 2026-06-27 374浏览
-
- golang MySQL实现对数据库表存储获取操作示例
- 2022-12-22 499浏览
-
- golang 基于 mysql 简单实现分布式读写锁
- 2023-01-07 384浏览
-
- 详解如何利用GORM实现MySQL事务
- 2023-01-07 184浏览
-
- Go语言实现操作MySQL的基础知识总结
- 2023-01-23 265浏览
