我正在编写一个 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'"
关于Python:执行带参数的存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34228152/