Skip to main content
 首页 » 编程设计

Python:执行带参数的存储过程

2025年05月04日8zhoujg

我正在编写一个 Python 脚本,该脚本将存储过程中的记录写入文本文件。我在执行带参数的存储过程时遇到问题。

我不确定我可以做些什么来使用两个参数执行这个存储过程。您可以在下方看到我遇到的错误。

如有任何见解,我们将不胜感激。

这是我的代码

# Import Python ODBC module 
import pyodbc 
 
# Create connection 
cnxn = pyodbc.connect(driver="{SQL Server}",server="<server>",database="<database>",uid="<username>",pwd="<password>") 
cursor = cnxn.cursor() 
 
# Execute stored procedure 
storedProc = "exec database..stored_procedure('param1', 'param2')" 
 
# Loop through records 
for irow in cursor.execute(storedProc): 
 
    # Create a new text file for each ID 
    myfile = open('c:/Path/file_' + str(irow[0]) + '_' + irow[1] + '.txt', 'w') 
 
    # Write retrieved records to text file 
    myfile.write(irow[2]) 
 
    # Close the file 
    myfile.close() 

这里是错误

Traceback (most recent call lst): 
File "C:\Path\script.py", line 12, in <module> 
  for irow in cursor.execute(storedProc): 
      pyodbc.ProgrammingError: ('42000', "[4200] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'param1'. <102> <SQLExecDirectW>"> 

请您参考如下方法:

我能够通过从查询字符串中删除括号来修复语法错误。

# Execute stored procedure 
storedProc = "exec database..stored_procedure('param1', 'param2')" 

应该是

# Execute stored procedure 
storedProc = "exec database..stored_procedure 'param1','param2'"