当我尝试执行sql查询时出现错误

时间:2014-03-22 19:01:50

标签: python mysql

即便如此,如何解决这个问题:

cursor.execute("""SELECT * FROM Users AS t1
                          INNER JOIN Users_has_Users AS t ON t.Users_id = t1.id
                          INNER JOIN Users AS t2 ON t.Users_id1 = t2.id
                          WHERE t1.email = %s AND t1.id != t2.id AND t2.id >= %s
                          ORDER BY t2.name {}
                          LIMIT 10""".format(order), (email, since_id, limit))

错误:

not all arguments converted during string formatting

1 个答案:

答案 0 :(得分:1)

您不能使用SQL参数来插入 data 以外的任何内容;您不能将它用于任何SQL关键字,例如ASC,也不能用于limit参数。那是SQL参数的 point ;避免将其值解释为SQL。

使用字符串格式来插入排序方向和查询限制:

cursor.execute("""SELECT * FROM Users AS t1
                  INNER JOIN Users_has_Users AS t ON t.Users_id = t1.id
                  INNER JOIN Users AS t2 ON t.Users_id1 = t2.id
                  WHERE t1.email = %s AND t1.id != t2.id AND t2.id >= %s
                  ORDER BY t2.name {}
                  LIMIT {}""".format(order, limit), (email, since_id))

这假设您可以完全控制orderlimit的内容;永远不会从用户提供的数据中设置它,因为这样的字符串格式化会打开你的SQL注入攻击。