无法将python datetime.date对象与sqlite DATE匹配

我有一个带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:参数类型不受支持”的情况吗?

sdafffffffffffffff85 回答:无法将python datetime.date对象与sqlite DATE匹配

如果您阅读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] )
本文链接:https://www.f2er.com/3163695.html

大家都在问