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

如何在Python中使用SQLite筛选当日日期的产品数据

解决SQLite查询当日产品数据的问题

问题根源

你直接用f-string拼接date对象到SQL语句中,会导致生成的SQL里日期没有单引号,无法匹配数据库中的日期格式;同时这种字符串拼接方式存在SQL注入风险。另外你重复赋值date变量,覆盖了导入的date类,虽当前不影响,但易引发后续问题。

正确解决方案

方案1:参数化查询(推荐)

SQLite支持通过占位符?传递参数,Python的sqlite3会自动处理类型转换,既安全又能避免格式问题:

import sqlite3
from datetime import date

# 获取当日日期,避免变量名覆盖导入的date类
today = date.today()
con = sqlite3.connect('test.db')
cur = con.cursor()

# 用?作为参数占位符
sql_q = '''SELECT date, name FROM `table` WHERE date = ?'''
# 以元组形式传递参数,sqlite3自动转换日期格式
table = cur.execute(sql_q, (today,))

for row in table:
    print(row)

# 操作完成后关闭连接
con.close()

方案2:手动转换日期为字符串(不推荐,存在注入风险)

若一定要拼接字符串,需把日期对象转为YYYY-MM-DD格式的字符串并添加单引号:

import sqlite3
from datetime import date

today = date.today()
# 转换为数据库兼容的字符串格式
today_str = today.strftime('%Y-%m-%d')
con = sqlite3.connect('test.db')
cur = con.cursor()

# 表名table是SQL关键字,需用反引号包裹
sql_q = f'''SELECT date, name FROM `table` WHERE date = '{today_str}''''
table = cur.execute(sql_q)

for row in table:
    print(row)

con.close()

额外提示

  • 表名table是SQLite关键字,直接使用会报错,需用反引号`包裹,或更换为非关键字的表名。
  • 推荐用with语句自动管理数据库连接,无需手动关闭:
import sqlite3
from datetime import date

today = date.today()

with sqlite3.connect('test.db') as con:
    cur = con.cursor()
    sql_q = '''SELECT date, name FROM `table` WHERE date = ?'''
    table = cur.execute(sql_q, (today,))
    for row in table:
        print(row)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 22:50:36