我在Django 1.8工作。我目前正在使用django.db.connection
运行以下不安全查询:
cursor = connection.cursor()
param = 'cost' # Actually obtained as a GET parameter
query = "SELECT date, pct_id, SUM(%s) as val " % param
query += "FROM mytable "
query += "GROUP BY pct_id, date ORDER BY date"
cursor.execute(query)
这样可行,但显然容易受到SQL注入攻击。相反,我希望在将param
传递给查询字符串之前将其转义。
所以我试试这个:
query = "SELECT date, pct_id, SUM(%s) as val "
query += "FROM mytable "
query += "GROUP BY pct_id, date ORDER BY date"
cursor.execute(query, param)
然而,这给了我以下错误:
TypeError: not all arguments converted during string formatting
如何安全地逃避此参数?