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

如何在MS SQL查询中添加one_yrs_ago变量实现时间范围筛选

正确将Python日期变量嵌入MS SQL查询的方法

嘿,我看到你在把Python的日期变量加到MS SQL查询时遇到了语法问题,咱们一步步来修正它:

首先先指出你代码里的两个核心错误:

  • 重复使用WHERE关键字:在已经有一个WHERE条件的情况下,后续的过滤条件只需要用AND连接,不需要再次写WHERE。
  • 字符串与变量拼接错误:Python中不能直接用空格把字符串和变量连在一起,而且MS SQL中日期值需要用单引号包裹,同时要保证日期格式能被数据库识别。

下面是两种正确的实现方式:

方式一:使用f-string格式化(简洁直观,适合简单场景)

from datetime import datetime
from dateutil.relativedelta import relativedelta

one_yrs_ago = datetime.now() - relativedelta(years=1)
# 将日期格式化为MS SQL兼容的ISO格式(YYYY-MM-DD HH:MM:SS)
formatted_date = one_yrs_ago.strftime('%Y-%m-%d %H:%M:%S')

# 使用f-string拼接查询语句,注意日期值的单引号
query = f"""
SELECT Master_Sub_Account, cAccountTypeDescription, Debit, Credit 
FROM [Kyle].[dbo].[PostGL] AS genLedger
INNER JOIN [Kyle].[dbo].[Accounts] 
    ON Accounts.AccountLink = genLedger.AccountLink 
INNER JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes 
    ON Accounts.iAccountType = AccountTypes.idGLAccountType
WHERE genLedger.AccountLink NOT IN (161,162,163,164,165,166,167,168,122)
  AND genLedger.TxDate > '{formatted_date}'
"""

方式二:参数化查询(强烈推荐,安全防注入)

这种方式不需要手动处理日期格式,数据库驱动会自动完成类型转换,同时能有效避免SQL注入风险:

from datetime import datetime
from dateutil.relativedelta import relativedelta
import pyodbc  # 假设你使用pyodbc连接MS SQL数据库

one_yrs_ago = datetime.now() - relativedelta(years=1)

# 用?作为参数占位符
query = """
SELECT Master_Sub_Account, cAccountTypeDescription, Debit, Credit 
FROM [Kyle].[dbo].[PostGL] AS genLedger
INNER JOIN [Kyle].[dbo].[Accounts] 
    ON Accounts.AccountLink = genLedger.AccountLink 
INNER JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes 
    ON Accounts.iAccountType = AccountTypes.idGLAccountType
WHERE genLedger.AccountLink NOT IN (161,162,163,164,165,166,167,168,122)
  AND genLedger.TxDate > ?
"""

# 建立连接并执行查询,将参数传入execute方法
conn = pyodbc.connect('你的数据库连接字符串')
cursor = conn.cursor()
cursor.execute(query, (one_yrs_ago,))
results = cursor.fetchall()

# 记得关闭连接
cursor.close()
conn.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:24:06