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

使用Python pymssql向SQL Server传datetime参数执行CDC查询报错如何解决

报错原因

你收到语法报错的核心问题出在SQL语句拼接环节:

  • 直接使用f-string将Python的datetime对象拼接进SQL时,没有用单引号包裹日期值。Python的datetime对象转字符串后格式为YYYY-MM-DD HH:MM:SS,直接插入SQL后会生成类似SET @begin_time = 2024-05-20 11:30:00;的非法语句,SQL Server解析到空格后的数字11时无法识别,就触发了Incorrect syntax near '11'的报错。
  • 额外风险:直接字符串拼接SQL还存在SQL注入隐患,也容易受不同环境的日期格式差异影响出现异常,不推荐使用。
修复方案

建议使用pymssql支持的参数化查询传参,框架会自动处理数据类型转换,无需手动处理日期格式:

from datetime import datetime, timedelta
end_date = datetime.now()
start_date = datetime.now() + timedelta(hours=-1)

cur = conn.cursor()
# SQL语句中用%s作为参数占位符
query =  """DECLARE @begin_time datetime, @end_time datetime, @from_lsn binary(10), @to_lsn binary(10);  
                SET @begin_time = %s;  
                SET @end_time = %s; 
                SET @from_lsn = sys.fn_cdc_map_time_to_lsn('smallest greater than or equal', @begin_time);  
                SET @to_lsn = sys.fn_cdc_map_time_to_lsn('largest less than or equal', @end_time); 
                SELECT * FROM cdc.fn_cdc_get_all_changes_dbo_users (@from_lsn, @to_lsn, 'all');"""
# 按占位符顺序传入参数元组即可
cur.execute(query, (start_date, end_date))
output = cur.fetchall()
print(output)
conn.close()

如果需要临时快速修复,可以把f-string中的{start_date}、{end_date}用单引号包裹为'{start_date}'、'{end_date}',但该方案兼容性和安全性都远低于参数化查询,不建议长期使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:39:03