TypeError 不是在字符串格式化期间转换的所有参数,但没有计算任何字符串



我通过以下方式进行数据库查询:

class AllData(APIView):
def get(self, request, ids=None):
followers = self.request.GET
follower_ids = []
for x in followers:
follower_ids.append(followers[x])
with connection.cursor() as cursor:
cursor.execute("SELECT authapi_user.id, authapi_user.first_name, authapi_tweet.tweet_text 
FROM authapi_tweet 
INNER JOIN authapi_user 
ON authapi_user.id = authapi_tweet.author_id 
WHERE authapi_tweet.author_id=? 
ORDER BY created_on DESC", follower_ids)
table = cursor.fetchall()
return Response(table)

我收到以下错误:

并非所有参数在字符串格式化期间转换

根据我在网上发现的情况,在计算字符串时会发生这种情况,但传递到 WHERE 子句中查询中的列表是 int 列表,例如 [1,2,3]。

当查询中与之进行比较的值也是数据库中的 int 时,应该如何格式化此变量?

我还测试了这段代码,同时在 WHERE 子句中放置了一个静态数字,所以我知道问题出在插入变量的特定行上。

在 sqlite 中,您可以使用像WHERE id in (1,3,5,7)这样的语法来搜索列表(而不是 python 列表!我还没有找到一种参数化的方法。

一种解决方案是使用字符串格式方法构建查询;一个简单的示例:

ids = [2,4,6]
idlist = ','.join(str(i) for i in ids)
query = "SELECT * from t1 WHERE id in ({0})".format(ids)
db.execute(query)

但是等等:这将公开SQL注入的代码。假设代码中的 id 都是整数,那么在创建/提交查询之前,有多种方法可以创建仅包含整数的有效、安全的"idlist"。

最新更新