You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python+SQLite3日期范围查询遇TypeError参数错误,求解决方案

解决SQLite3 execute()的TypeError问题

嘿,这个错误我之前也踩过坑!问题出在cursor.execute()的参数传递方式上,咱们来一步步捋清楚:

错误原因

SQLite的cursor.execute()方法只接受两个参数:第一个是SQL语句字符串,第二个是包含所有占位符对应值的序列(比如元组、列表)。你现在直接把since和dateuntil作为两个独立参数传进去,相当于给了方法3个参数(SQL语句+since+dateuntil),这就触发了TypeError。

修正后的代码

只需要把参数打包成一个元组传进去就行,另外记得确保你已经导入了datetime模块哦:

import datetime
# 假设你的connect_db()函数已经正确定义
from your_module import connect_db

since = input("Enter date since = ") 
dateuntil = input("Enter date until = ") 

year, month, day = map(int, since.split('-')) 
since = datetime.date(year, month, day) 

year, month, day = map(int, dateuntil.split('-')) 
dateuntil = datetime.date(year, month, day) 

connection, cursor = connect_db() 
# 把参数打包成元组,放在第二个参数的位置
cursor.execute("select * from dates where myDate BETWEEN ? AND ?;", (since, dateuntil)) 
alldata = cursor.fetchall()

# 别忘了最后关闭连接哦
connection.close()

额外小提示

  • 用参数化查询(就是用?占位符)不仅能避免这类语法错误,还能有效防止SQL注入攻击,这是操作数据库的最佳实践~
  • 如果你的myDate字段存储的是字符串格式的日期,可能需要先把datetime.date对象转换成对应的字符串格式(比如since.strftime('%Y-%m-%d')),确保和数据库里的格式匹配。

内容的提问来源于stack exchange,提问作者Tiffany Arasya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:27:32