与聚合表达式一起使用时安全地转义输入参数?

时间:2015-06-22 15:47:21

标签: python django

我在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

如何安全地逃避此参数?

0 个答案:

没有答案