我有一个包含 DATE 列的 sqlite 数据库,我无法通过 python 中的 SQL 进行匹配。 我从 https://docs.python.org/3/library/sqlite3.html#module-functions-and-constants 阅读了文档并尝试如下:
import sqlite3
import datetime
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("create table test(d date, ts timestamp)")
today = datetime.date.today()
now = datetime.datetime.now()
cur.execute("insert into test(d, ts) values (?, ?)", (today, now))
cur.execute('select current_date as "d [date]" from test') #No errors
cur.execute('select current_date as "d [date]" from test where current_date = ?', today ) #ValueError: parameters are of unsupported type
r = cur.fetchall()
print(r)
con.close()
有人可以解释为什么我在第二个 SQL 语句上收到“ValueError:参数的类型不受支持”吗?
最佳答案
如果您阅读 documentation您会看到 execute
需要一个元组,其中包含语句中每个问号的一个元素。
如果你把它改成
cur.execute('select current_date as "d [date]" from test where current_date = ?', (today,) )
它会起作用的。请注意项目后面的 ,
,这是避免其被“优化”为单个元素所必需的。您可以使用列表作为替代方案:
cur.execute('select current_date as "d [date]" from test where current_date = ?', [today] )
关于python - 无法将 python datetime.date 对象与 sqlite DATE 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58701138/