前言
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 pymysql conn = 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
#! /usr/bin/env python # -*- coding:utf-8 -*- # __author__ = "TKQ" import pymysql conn = 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() #获取自增id new_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 pymysql conn = 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、调用无参存储过程
#! /usr/bin/env python # -*- coding:utf-8 -*- # __author__ = "TKQ" import pymysql conn = 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_1 conn.commit() cursor.close() conn.close()
b、调用有参存储过程
#! /usr/bin/env python # -*- coding:utf-8 -*- # __author__ = "TKQ" import pymysql conn = 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_1 conn.commit() cursor.close() conn.close()
三、关于pymysql防注入
1、字符串拼接查询,造成注入
正常查询语句:
#! /usr/bin/env python # -*- coding:utf-8 -*- # __author__ = "TKQ" import pymysql conn = 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_1 conn.commit() cursor.close() conn.close()
构造注入语句:
#! /usr/bin/env python # -*- coding:utf-8 -*- # __author__ = "TKQ" import pymysql conn = 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_1 conn.commit() cursor.close() conn.close()
2、避免注入,使用pymysql提供的参数化语句
正常参数化查询
#! /usr/bin/env python # -*- coding:utf-8 -*- # __author__ = "TKQ" import pymysql conn = 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_1 conn.commit() cursor.close() conn.close()
构造注入,参数化查询注入失败。
#! /usr/bin/env python # -*- coding:utf-8 -*- # __author__ = "TKQ" import pymysql conn = 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_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 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 pymysql conn = 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简化连接过程
每次都连接关闭很麻烦,使用上下文管理,简化连接过程
#! /usr/bin/env python # -*- coding:utf-8 -*- # __author__ = "TKQ" import pymysql import contextlib #定义上下文管理器,连接后自动关闭连接 @contextlib.contextmanager def 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() # 执行sql with 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模块详解相关文章请关注PHP中文网!

Python和C 各有優勢,選擇應基於項目需求。 1)Python適合快速開發和數據處理,因其簡潔語法和動態類型。 2)C 適用於高性能和系統編程,因其靜態類型和手動內存管理。

選擇Python還是C 取決於項目需求:1)如果需要快速開發、數據處理和原型設計,選擇Python;2)如果需要高性能、低延遲和接近硬件的控制,選擇C 。

通過每天投入2小時的Python學習,可以有效提升編程技能。 1.學習新知識:閱讀文檔或觀看教程。 2.實踐:編寫代碼和完成練習。 3.複習:鞏固所學內容。 4.項目實踐:應用所學於實際項目中。這樣的結構化學習計劃能幫助你係統掌握Python並實現職業目標。

在兩小時內高效學習Python的方法包括:1.回顧基礎知識,確保熟悉Python的安裝和基本語法;2.理解Python的核心概念,如變量、列表、函數等;3.通過使用示例掌握基本和高級用法;4.學習常見錯誤與調試技巧;5.應用性能優化與最佳實踐,如使用列表推導式和遵循PEP8風格指南。

Python適合初學者和數據科學,C 適用於系統編程和遊戲開發。 1.Python簡潔易用,適用於數據科學和Web開發。 2.C 提供高性能和控制力,適用於遊戲開發和系統編程。選擇應基於項目需求和個人興趣。

Python更適合數據科學和快速開發,C 更適合高性能和系統編程。 1.Python語法簡潔,易於學習,適用於數據處理和科學計算。 2.C 語法複雜,但性能優越,常用於遊戲開發和系統編程。

每天投入兩小時學習Python是可行的。 1.學習新知識:用一小時學習新概念,如列表和字典。 2.實踐和練習:用一小時進行編程練習,如編寫小程序。通過合理規劃和堅持不懈,你可以在短時間內掌握Python的核心概念。

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Atom編輯器mac版下載
最受歡迎的的開源編輯器

禪工作室 13.0.1
強大的PHP整合開發環境