在Python中,當用pymysql庫,或者MySQLdb庫進行數據庫查詢時,為了防止sql注入,可以在execute的時候,把參數單獨帶進去,例如:
def execute_v1():
config = {
'user': 'root',
'password': 'password1',
'host': '127.0.0.1',
'database': 'selfmoe',
'port': 3307,
'charset': 'utf8'
}
import pymysql # 打開數據庫連接
cnx = pymysql.connect(**config)
cur = cnx.cursor()
cur.execute('select title,id from post where title =%(title)s', dict(title="**'*"))
ret = cur.fetchall()
print ret
cur.close()
cnx.close()
return ret
execute_v1()
cur.execute('select title,id from post where title =%(title)s', dict(title="**'*"))
這行中,title這個參數是以args的形式傳進去的
查看pymysql的源碼發現,當有args參數時,pymysql會做以下邏輯:
- 如果是入參是unicode,encode為utf8
- 如果是字符串,在兩邊加單引號
- 使用
escape_string
(from pymysql import escape_string)函數對字符串進行轉義 - 然后通過%來拼合字符串,得到最終的sql
所以
- 使用args參數,其實和自己手動轉義的效果是一樣的,最終傳給mysql的也是只有一個sql字符串。不過使用args可以把轉義部分交給pymysql,這樣安全性,穩定性更好,避免自己漏了轉義,避免自己處理轉義的異常情況。