[英]Is it safe to execute SQL query like this in Python using 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命令字符串的方式取決於數據庫(例如,sqlite使用?
)。
根據MySQLdb文檔 ,您可以使用paramstyle
參數來設置格式化字符串( format
或pyformat
)的首選方式。
您的問題中的第一個示例似乎不受支持。 無論如何,我會說,只要你不像上一個例子那樣格式化整個字符串,你就可以安全,因為可以假設查詢參數將被正確轉義。
您的insert語句應該明確指定要設置的字段名稱,以防止模式更改中斷。 此外,我發現你的代碼太重復了。 我會寫插入更像這樣的東西:
cursor.execute \
(
"insert into "
+
TABLE_BIZ_NAME
+
"("
+
", ".join(biz_info.keys())
+
") values ("
+
", ".join(("%s",) * len(biz_info))
+
")",
biz_info.values()
)
這樣,在創建biz_info dict時,只需要列出一次字段名稱。 任何未來的變化只需要在那里進行更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.