我注意到大多數的消息來源說,以最佳實踐來執行SQL語句在Python是這樣的:使用MySQLdb在Python中執行像這樣的SQL查詢是否安全?
cursor.execute('select * from coworkers where name = :1 and clue > :2', [ name, clue_threshold ])
其他消息來源說
cursor.execute("select * from coworkers where name = %s and clue > %s", (name, clue_threshold))
我認爲這是非常相似的。
無論如何,我一直在做的是創建一個字典和存儲值。例如,初始字典biz_info
看起來是這樣的:
biz_info = {
'business' : None,
'name' : None,
'neighborhood' : None,
'address' : None,
'city' : None,
'state' : None,
'zip_code' : None,
'latitude' : None,
'longitude' : None,
'phone' : None,
'url' : None,
'yelp_url' : None,
}
然後我執行SQL語句這樣
execute_sql(cur, "insert into " + TABLE_BIZ_NAME + """ values (
NULL,
%(name)s,
%(neighborhood)s,
%(address)s,
%(city)s,
%(state)s,
%(zip_code)s,
%(latitude)s,
%(longitude)s,
%(phone)s,
%(url)s,
%(yelp_url)s,
NULL
)"""
, biz_info)
這是對SQL注入安全嗎?我想使用字典來存儲信息,因爲它更容易管理。
說實話,我並不甚至完全知道什麼兩者的區別:一個%
,,
,%s
,%d
和%()s
意味着參數化查詢。基本上我所知道的是不使用
cursor.execute("select * from coworkers where name = '%s' and clue > %d" % (name, clue_threshold))
「這對sql注入安全嗎?」。是。 「我甚至不完全確定在參數化查詢中使用%,,,%s,%d和%()s的意義是什麼」。這是否意味着你在問關於Python DB-API的規則?你問這個http://www.python.org/dev/peps/pep-0249/? – 2012-02-07 22:17:47