前言
pymsql是Python中 *** 作MysqL的模块,其使用方法和MysqLdb几乎相同。但目前pyMysqL支持python3.x而后者不支持3.x版本。
本文测试python版本:2.7.11。MysqL版本:5.6.24
一、安装
pip3 install pyMysqL
二、使用 *** 作
1、执行sql
#!/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、获取查询数据
#! /usr/bin/env python# -*- Coding:utf-8 -*-# __author__ = "TKQ"import pyMysqLconn = pyMysqL.connect(host='127.0.0.1',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
#! /usr/bin/env python# -*- Coding:utf-8 -*-# __author__ = "TKQ"import pyMysqLconn = pyMysqL.connect(host='127.0.0.1',db='tkq1')cursor = conn.cursor()effect_row = cursor.executemany("insert into tb7(user,[("u3","u3pass","11113"),("u4","u4pass","22224")])conn.commit()cursor.close()conn.close()#获取自增IDnew_ID = cursor.lastrowID print new_ID
4、移动游标
*** 作都是靠游标,那对游标的控制也是必须的
注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:cursor.scroll(1,mode='relative') # 相对当前位置移动cursor.scroll(2,mode='absolute') # 相对绝对位置移动
5、fetch数据类型
关于默认获取的数据是元祖类型,如果想要或者字典类型的数据,即:
#! /usr/bin/env python# -*- Coding:utf-8 -*-# __author__ = "TKQ"import pyMysqLconn = pyMysqL.connect(host='127.0.0.1',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、调用无参存储过程
#! /usr/bin/env python# -*- Coding:utf-8 -*-# __author__ = "TKQ"import pyMysqLconn = pyMysqL.connect(host='127.0.0.1',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、调用有参存储过程
#! /usr/bin/env python# -*- Coding:utf-8 -*-# __author__ = "TKQ"import pyMysqLconn = pyMysqL.connect(host='127.0.0.1',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、字符串拼接查询,造成注入
正常查询语句:
#! /usr/bin/env python# -*- Coding:utf-8 -*-# __author__ = "TKQ"import pyMysqLconn = pyMysqL.connect(host='127.0.0.1',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()
构造注入语句:
#! /usr/bin/env python# -*- Coding:utf-8 -*-# __author__ = "TKQ"import pyMysqLconn = pyMysqL.connect(host='127.0.0.1',db='tkq1')cursor = conn.cursor()user="u1' or '1'-- "passwd="u1pass"sql="select 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提供的参数化语句
正常参数化查询
#! /usr/bin/env python# -*- Coding:utf-8 -*-# __author__ = "TKQ"import pyMysqLconn = pyMysqL.connect(host='127.0.0.1',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()
构造注入,参数化查询注入失败。
#! /usr/bin/env python# -*- Coding:utf-8 -*-# __author__ = "TKQ"import pyMysqLconn = pyMysqL.connect(host='127.0.0.1',db='tkq1')cursor = conn.cursor()user="u1' or '1'-- "passwd="u1pass"#执行参数化查询row_count=cursor.execute("select user,passwd))#内部执行参数化生成的SQL语句,对特殊字符进行了加\转义,避免注入语句生成。# sql=cursor.mogrify("select 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到存储过程执行语句。
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 ;
set @nID1=12;set @nID2=15;set @callsql = 'select * from tb7 where nID>? and nID<?';CALL proc_sql(@nID1,@nID2,@callsql)
pymsql中调用
#! /usr/bin/env python# -*- Coding:utf-8 -*-# __author__ = "TKQ"import pyMysqLconn = pyMysqL.connect(host='127.0.0.1',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简化连接过程
每次都连接关闭很麻烦,使用上下文管理,简化连接过程
#! /usr/bin/env python# -*- Coding:utf-8 -*-# __author__ = "TKQ"import pyMysqLimport contextlib#定义上下文管理器,连接后自动关闭连接@contextlib.contextmanagerdef MysqL(host='127.0.0.1',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中pyMysqL模块的全部内容,希望对大家学习或使用python能有一定的帮助,如果有疑问大家可以留言交流。
总结以上是内存溢出为你收集整理的Python中 *** 作mysql的pymysql模块详解全部内容,希望文章能够帮你解决Python中 *** 作mysql的pymysql模块详解所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)