0
我想知道如何安全地參數化python中的動態mysql查詢。動態的,我的意思是根據if語句如何評估而變化。如何安全地參數化動態python mysql查詢?
我明白如何使用逗號而不是百分號來參數化python中的mysql查詢,如下所示。
c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))
這裏是一個'動態查詢'的例子。我正在尋找比使用百分號更安全的方法。
def queryPhotos(self, added_from, added, added_to):
sql = "select * from photos where 1=1 "
if added_from is not None:
sql = sql + "and added >= '%s' " % added_from
if added is not None:
sql = sql + "and added = '%s' " % added
if added_to is not None:
sql = sql + "and added <= '%s' " % added_to
謝謝你的洞察力。
用問號組裝一個sql查詢字符串,即'query ='select * from table where thing =?和otherthing =?'',然後沿'c.execute(查詢,[param1.param2])行 – Nullman