我正在使用pg8000
通过 Python 连接到 PostgreSQL 数据库。我希望能够通过以下cursor.execute
方法将日期作为参数发送:
def info_by_month(cursor, year, month):
query = """
SELECT *
FROM info
WHERE date_trunc('month', info.created_at) =
date_trunc('month', '%s-%s-01')
"""
cursor.execute(query, (year, month))
return cursor
这将引发错误:InterfaceError: '%s' not supported in a quoted string within the query string
。可以使用 Python 的字符串格式在其中插入日期。使用字符串格式化迷你语言提供了一种数据验证措施来防止 SQL 注入攻击,但它仍然很丑陋。
def info_by_month(cursor, year, month):
query = """
SELECT *
FROM info
WHERE date_trunc('month', info.created_at) =
date_trunc('month', '{:04}-{:02}-01')
""".format(year, month)
cursor.execute(query)
return cursor
如何将带引号的字符串发送到cursor.execute
方法中?