Psycopg2 - SQL 脚本不返回任何输出

Psycopg2 - SQL script returning no output

我试图将一些参数作为变量传递给 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))

以上 returns 没有输出,但我知道此 SQL 脚本存在数据

执行查询后,您需要获取结果:

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))

为了使用列表作为参数,您可以使用 INtuple:

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

请务必阅读 docs,因为其中包含很多有价值的信息。