Python MySQLdb 執行sql語句時的參數傳遞
阿新 • • 發佈:2019-05-12
pytho 內容 orange passwd lec mysqldb clas roo oot
使用MySQLdb連接數據庫執行sql語句時,有以下幾種傳遞參數的方法。
1.不傳遞參數
conn = MySQLdb.connect(user="root",passwd="123456",host="192.168.101.23",db="cmdb")
orange_id = 98
sql = "select * from orange where id=%s" % orange_id
cursor = conn.cursor(sql)
cursor.execute()
2.傳遞參數
color = "yellow"
sql = "select * from orange where color = %s"
cursor.execute(sql, color)
註意此處的占位符是%s
,無論是字符串、數字或者其他類型,都是這個占位符。
另外, %s
不能加引號,如‘%s‘
, 這是錯誤的寫法。
與第一種寫法,有什麽區別呢?
兩者區別是對變量的解析:
第一種寫法,使用百分號
%
, 是用Python解釋器對%s
執行相應的替換。這種方法存在漏洞,有些時候不能正常解析,比如包含某些特殊字符,甚至會造成註入攻擊的風險。第二種,變量是作為execute的參數傳入的,由MySQLdb的內置方法把變量解釋成合適的內容。
一般情況下,建議使用第二種方法,把變量作為參數傳遞給execute
。
3.使用字典dict類型傳遞參數
sql = "select * from orange where %(color)s, %(weight)s"
values = {"color": "yellow", "weight": 30}
cursor.execute(sql, values)
這種方式,傳遞的參數對應關系比較清晰。尤其是參數比較多時,使用字典,可以保證傳遞參數的順序正確。
Python MySQLdb 執行sql語句時的參數傳遞