python使用pysql操作MySQL数据库
前言
pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。但目前pymysql支持python3.x而后者不支持3.x版本。
本文测试python版本:2.7.11。mysql版本:5.6.24
一、安装
|
1
|
pip3 install pymysql |
二、使用操作
1、执行SQL
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
#!/usr/bin/env pytho# -*- coding:utf-8 -*-import pymysql # 创建连接conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1', charset='utf8')# 创建游标cursor = conn.cursor() # 执行SQL,并返回收影响行数effect_row = cursor.execute("select * from tb7") # 执行SQL,并返回受影响行数#effect_row = cursor.execute("update tb7 set pass = '123' where nid = %s", (11,)) # 执行SQL,并返回受影响行数,执行多次#effect_row = cursor.executemany("insert into tb7(user,pass,licnese)values(%s,%s,%s)", [("u1","u1pass","11111"),("u2","u2pass","22222")]) # 提交,不然无法保存新建或者修改的数据conn.commit() # 关闭游标cursor.close()# 关闭连接conn.close() |
注意:存在中文的时候,连接需要添加charset='utf8',否则中文显示乱码。
2、获取查询数据
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#! /usr/bin/env python# -*- coding:utf-8 -*-# __author__ = "TKQ"import pymysqlconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')cursor = conn.cursor()cursor.execute("select * from tb7")# 获取剩余结果的第一行数据row_1 = cursor.fetchone()print row_1# 获取剩余结果前n行数据# row_2 = cursor.fetchmany(3)# 获取剩余结果所有数据# row_3 = cursor.fetchall()conn.commit()cursor.close()conn.close() |
3、获取新创建数据自增ID
可以获取到最新自增的ID,也就是最后插入的一条数据ID
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#! /usr/bin/env python# -*- coding:utf-8 -*-# __author__ = "TKQ"import pymysqlconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')cursor = conn.cursor()effect_row = cursor.executemany("insert into tb7(user,pass,licnese)values(%s,%s,%s)", [("u3","u3pass","11113"),("u4","u4pass","22224")])conn.commit()cursor.close()conn.close()#获取自增idnew_id = cursor.lastrowid print new_id |
4、移动游标
操作都是靠游标,那对游标的控制也是必须的
|
1
2
3
4
|
注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:cursor.scroll(1,mode='relative') # 相对当前位置移动cursor.scroll(2,mode='absolute') # 相对绝对位置移动 |
5、fetch数据类型
关于默认获取的数据是元祖类型,如果想要或者字典类型的数据,即:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#! /usr/bin/env python# -*- coding:utf-8 -*-# __author__ = "TKQ"import pymysqlconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')#游标设置为字典类型cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)cursor.execute("select * from tb7")row_1 = cursor.fetchone()print row_1 #{u'licnese': 213, u'user': '123', u'nid': 10, u'pass': '213'}conn.commit()cursor.close()conn.close() |
6、调用存储过程
a、调用无参存储过程
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#! /usr/bin/env python# -*- coding:utf-8 -*-# __author__ = "TKQ"import pymysqlconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')#游标设置为字典类型cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)#无参数存储过程cursor.callproc('p2') #等价于cursor.execute("call p2()")row_1 = cursor.fetchone()print row_1conn.commit()cursor.close()conn.close() |
b、调用有参存储过程
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#! /usr/bin/env python# -*- coding:utf-8 -*-# __author__ = "TKQ"import pymysqlconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')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_1conn.commit()cursor.close()conn.close() |
三、关于pymysql防注入
1、字符串拼接查询,造成注入
正常查询语句:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#! /usr/bin/env python# -*- coding:utf-8 -*-# __author__ = "TKQ"import pymysqlconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')cursor = conn.cursor()user="u1"passwd="u1pass"#正常构造语句的情况sql="select user,pass from tb7 where user='%s' and pass='%s'" % (user,passwd)#sql=select user,pass from tb7 where user='u1' and pass='u1pass'row_count=cursor.execute(sql) row_1 = cursor.fetchone()print row_count,row_1conn.commit()cursor.close()conn.close() |
构造注入语句:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#! /usr/bin/env python# -*- coding:utf-8 -*-# __author__ = "TKQ"import pymysqlconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')cursor = conn.cursor()user="u1' or '1'-- "passwd="u1pass"sql="select user,pass from tb7 where user='%s' and pass='%s'" % (user,passwd)#拼接语句被构造成下面这样,永真条件,此时就注入成功了。因此要避免这种情况需使用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_1conn.commit()cursor.close()conn.close() |
2、避免注入,使用pymysql提供的参数化语句
正常参数化查询
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#! /usr/bin/env python# -*- coding:utf-8 -*-# __author__ = "TKQ"import pymysqlconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')cursor = conn.cursor()user="u1"passwd="u1pass"#执行参数化查询row_count=cursor.execute("select user,pass from tb7 where user=%s and pass=%s",(user,passwd))row_1 = cursor.fetchone()print row_count,row_1conn.commit()cursor.close()conn.close() |
构造注入,参数化查询注入失败。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#! /usr/bin/env python# -*- coding:utf-8 -*-# __author__ = "TKQ"import pymysqlconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')cursor = conn.cursor()user="u1' or '1'-- "passwd="u1pass"#执行参数化查询row_count=cursor.execute("select user,pass from tb7 where user=%s and pass=%s",(user,passwd))#内部执行参数化生成的SQL语句,对特殊字符进行了加\转义,避免注入语句生成。# sql=cursor.mogrify("select user,pass from tb7 where user=%s and pass=%s",(user,passwd))# print sql#select user,pass from tb7 where user='u1\' or \'1\'-- ' and pass='u1pass'被转义的语句。row_1 = cursor.fetchone()print row_count,row_1conn.commit()cursor.close()conn.close() |
结论:excute执行SQL语句的时候,必须使用参数化的方式,否则必然产生SQL注入漏洞。
3、使用存mysql储过程动态执行SQL防注入
使用MYSQL存储过程自动提供防注入,动态传入SQL到存储过程执行语句。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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 tb2 where nid>? and nid<?'; 传入的值为字符串,?为占位符-- 用@p1,和@p2填充占位符 EXECUTE myprod USING @nid1,@nid2; DEALLOCATE prepare myprod;END\\delimiter ; |
|
1
2
3
4
|
set @nid1=12;set @nid2=15;set @callsql = 'select * from tb7 where nid>? and nid<?';CALL proc_sql(@nid1,@nid2,@callsql) |
pymsql中调用
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#! /usr/bin/env python# -*- coding:utf-8 -*-# __author__ = "TKQ"import pymysqlconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')cursor = conn.cursor()mysql="select * from tb7 where nid>? and nid<?"cursor.callproc('proc_sql', args=(11, 15, mysql))rows = cursor.fetchall()print rows #((12, 'u1', 'u1pass', 11111), (13, 'u2', 'u2pass', 22222), (14, 'u3', 'u3pass', 11113))conn.commit()cursor.close()conn.close() |
四、使用with简化连接过程
每次都连接关闭很麻烦,使用上下文管理,简化连接过程
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#! /usr/bin/env python# -*- coding:utf-8 -*-# __author__ = "TKQ"import pymysqlimport contextlib#定义上下文管理器,连接后自动关闭连接@contextlib.contextmanagerdef mysql(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1',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()# 执行sqlwith mysql() as cursor: print(cursor) row_count = cursor.execute("select * from tb7") row_1 = cursor.fetchone() print row_count, row_1 |
python使用pysql操作MySQL数据库的更多相关文章
- Python使用DB-API操作MySQL数据库
Python提供了一个标准数据库API,称为DB-API,用于处理基于SQL的数据库.与任何底层数据库的交互都可以使用DB-API,因为DB-API在代码与驱动程序之间提供了一个抽象层,可以根据需要替 ...
- python开发_python操作mysql数据库
如果你还没有准备好开发环境,你不妨花上一小点时间去看看:python开发_mysqldb安装 本篇blog是有关python操作mysql数据的相关内容. 我做了一个demo: 先看运行效果: mys ...
- python web.py操作mysql数据库,实现对数据库的增删改查操作
使用web.py框架,实现对mysql数据库的增删改查操作: 该示例代码中连接的是本地数据库testdb,user表,表结构比较简单,只有两个字段:mobile和passwd,类型均为字符型 实际应用 ...
- python 2.7 操作mysql数据库 实例
create table msg(id int primary key auto_increment,title varchar(20),name varchar(60),content varcha ...
- python使用pymysql操作mysql数据库
1.安装pymysql pip install pymysql 2.数据库查询示例 import pymysql # 连接database conn =pymysql.connect(user=' , ...
- 【Python】Windows平台下Python、Pydev连接Mysql数据库
Mysql数据库是跨平台的,不是说Python一定就要连接Mongodb. Python连接Mysql数据库是非常easy的. 首先,你要配置好Python的开发环境,详见<[Python]Wi ...
- [Python] 学习笔记之MySQL数据库操作
1 Python标准数据库接口DB-API介绍 Python标准数据库接口为 Python DB-API,它为开发人员提供了数据库应用编程接口.Python DB-API支持很多种的数据库,你可以选择 ...
- python操作mysql数据库的相关操作实例
python操作mysql数据库的相关操作实例 # -*- coding: utf-8 -*- #python operate mysql database import MySQLdb #数据库名称 ...
- python【第十二篇下】操作MySQL数据库以及ORM之 sqlalchemy
内容一览: 1.Python操作MySQL数据库 2.ORM sqlalchemy学习 1.Python操作MySQL数据库 2. ORM sqlachemy 2.1 ORM简介 对象关系映射(英语: ...
- Windows下安装MySQLdb, Python操作MySQL数据库的增删改查
这里的前提是windows上已经安装了MySQL数据库,且配置完成,能正常建表能操作. 在此基础上仅仅需安装MySQL-python-1.2.4b4.win32-py2.7.exe就ok了.仅仅有1M ...
随机推荐
- 【Jenkins】Jenkins 运行权限问题
yum安装的Jenkins 配置文件默认位置/etc/sysconfig/jenkins 默认jenkins服务以jenkins用户运行,这时在jenkins执行maven脚本时可能会发生没有权限操作 ...
- Unity 2022.3.20f1新功能,异步实例化预制体Object.InstantiateAsync
今天查看Unity 2022.3.20f1更新日志,发现新增了个异步实例化的功能,这个功能解决了Unity历史上实例化预制体卡顿的痛点,简直不要太爽. 具体的API文档请点击跳转. 做了个简单的实例化 ...
- 使用OHOS SDK构建libxml2
参照OHOS IDE和SDK的安装方法配置好开发环境. 从github下载源码. 执行如下命令: git clone --depth=1 https://gitlab.gnome.org/GNOME/ ...
- java中DelayQueue的使用
目录 简介 DelayQueue DelayQueue的应用 总结 java中DelayQueue的使用 简介 今天给大家介绍一下DelayQueue,DelayQueue是BlockingQueue ...
- 攻防世界 debug
题目 分析过程 丢到PE里面 一开始,我看到下面的脱壳提示,以为是我没见过的壳,下载了相关工具脱壳--发现脱了后又出现没见过的脱壳提示,根据提示脱壳弄出来的东西怪怪的 卡题,查了资料 学到一个新知识点 ...
- Ansible 学习笔记 - 批量巡检站点 URL 状态
前言 不拖泥带水,不东拉西扯. 速战速决,五分钟学到一个工作用得上的技巧. 通过一个个具体的实战案例,来生动演示 Ansible 的用法. 需求 我需要定期巡检或定时监控我公司的所有站点的首页的可用性 ...
- .NET Aspire预览5版本 发布
2024年4月11日发布了.NET Aspire预览5版本,这个版本引入了对AWS的支持,并对Azure功能进行了改进.重点内容包括拆分Aspire.Hosting和Aspire.Hosting.Az ...
- Linux之识别HBA的WWN
一.概念 FC HBA,也即Fibre Channel Host Bus Adapter,光纤通道主机适配器,简称光纤适配器. 在FC网络环境中,主机需要和FC网络.FC存储设备(SAN磁盘阵列)连接 ...
- WAF 原理入门
WAF 入门 WAF 功能 WAF 全称叫 Web Application Firewall,和传统防火墙的区别是,它是工作在应用层的防火墙,主要对 web 请求/响应进行防护.那么 WAF 有什么功 ...
- CentOS 8 安装更新国内清华大学源手记【亲测成功】
一直和各种OS打交道,仍觉得自己是小白,故深知小白们的困惑和蛋碎,特此将安装更新源的细节和步骤做了详细整理,供大家参考.红字是命令和提示,深灰色代码框中是源配置,本文采用了清华大学CentOS 8的源 ...