Psycopg2 - 不返回输出的 SQL 脚本

我正在尝试将一些参数作为变量传递给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脚本存在数据


哔哔one
浏览 62回答 1
1回答

潇潇雨雨

执行查询后,您需要获取结果:records = cursor.fetchall()不要用于SQL查询非常重要,因为它容易受到SQL注入攻击;而是使用:formatquery = "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>>> 确保您阅读了文档,因为它们包含许多有价值的信息。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python