我试图将几个参数作为变量传递给SQL脚本,但返回输出时遇到了问题。
下面是我的代码:
start_date = '2020-03-01'
end_date = '2020-03-02'我将这些内容传递给下面的查询
cursor.execute('select bill_number from table
where created_at between {} and {}'.format(start_date, end_date))上面的内容不返回输出,但我知道此SQL脚本存在数据。
发布于 2020-03-10 09:04:36
执行查询后,您需要获取的结果:
records = cursor.fetchall()是非常重要的,您不将format用于SQL查询,因为它容易受到SQL注入攻击;相反,请使用:
query = "select bill_number from table where created_at between %s and %s"
cursor.execute(query, (start_date, end_date))
records = cursor.fetchall()如果要添加筛选器,只需调整查询并添加参数:
query = "select bill_number from table where created_at between %s and %s and product=%s"
cursor.execute(query, (start_date, end_date, product))为了使用列表作为参数,可以使用IN和tuple
>>> query = "select * from clients where added between %s and %s and score in %s"
>>> data = ('2019-01-01', '2020-03-01', tuple([1,2,3]))
>>> cursor.execute(query, data)
>>> rows = cursor.fetchall()
>>> len(rows)
32
>>> 一定要阅读文档,因为它们包含了许多有价值的信息。
https://stackoverflow.com/questions/60613992
复制相似问题