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

Python调用SQL Server存储过程报pyodbc语法错误,请求协助解决

问题分析与解决方案

核心错误原因

直接用字符串格式化拼接SQL语句,导致字符串类型的参数(邮箱、HTML内容)未被正确包裹引号,且HTML中的特殊字符(如单引号、点号等)破坏了SQL语法结构,引发Incorrect syntax near '.'错误。此外数据库连接字符串存在配置冲突。

分步修正

1. 修复数据库连接字符串

连接字符串同时指定了SQL Server认证(Username/Password)和Windows认证(Trusted_Connection=yes),二者只能选其一,且多余的双分号需删除:

# SQL Server认证写法
connection = pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};"
                "Server=MSS-ProdSQL-01;"
                "Database=ORTeam;"
                "Username=" + username + ";"
                "Password=" + password + ";")

# Windows认证写法(移除Username/Password)
# connection = pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};"
#                 "Server=MSS-ProdSQL-01;"
#                 "Database=ORTeam;"
#                 "Trusted_Connection=yes;")

2. 使用参数化查询调用存储过程

禁止直接拼接字符串到SQL语句中,改用pyodbc的参数化查询机制,自动处理字符串转义和引号包裹:

# 移除USE ORTeam(连接时已指定数据库),用?作为参数占位符
executesp = "EXEC cp.Send_Chargecode_Changes @emailto = ?, @emailhtml = ?"

# 执行时传入参数元组,pyodbc自动处理类型转义
connection_cursor.execute(executesp, (emailto, emailhtml))

3. 存储过程权限优化(可选)

存储过程中EXECUTE AS LOGIN = 'sa'可能导致权限过高或冲突,若当前连接用户已有调用sp_send_dbmail的权限,可移除该语句;若必须提权,需确保执行存储过程的用户拥有针对sa登录名的IMPERSONATE权限。

完整修正后的Python脚本

import pyodbc

username = '***'
password = '***'
emailto = 'example@domain.com'  # 替换为实际收件人
emailhtml = '<h1>测试HTML邮件</h1>'  # 替换为实际HTML内容

# 建立数据库连接(SQL Server认证)
connection = pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};"
                "Server=MSS-ProdSQL-01;"
                "Database=ORTeam;"
                "Username=" + username + ";"
                "Password=" + password + ";")
connection_cursor = connection.cursor()

# 参数化调用存储过程
executesp = "EXEC cp.Send_Chargecode_Changes @emailto = ?, @emailhtml = ?"
connection_cursor.execute(executesp, (emailto, emailhtml))

connection.autocommit = True
connection.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 00:45:59