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

标签 python sqlite

我有一个包含 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/

相关文章:

python - Dataframe 中两个对象之间的最小差异

ruby-on-rails - Ruby on Rails sqlite3-ruby gem 干扰 heroku push

android - 如何将解析的 JSON 保存到 SQLite Android

python - 从 pandas 数据框中识别相似数据集中的第一行

python - 在每行中填充第一个 NaN

python - 在 Pandas 数据框中使用多列作为索引

python - tensorflow 中的批量归一化在训练期间是否使用运行平均值?

database - 如何打开核心数据数据库?

C# SQLite : Do I need to deploy System. Data.SQLite.xml?

sql - 从 SQLite 中的 INSERT OR IGNORE 语句中查找自动递增的值