2015-12-11 42 views
2

我正在研究將記錄從存儲過程寫入文本文件的Python腳本。我在執行帶有參數的存儲過程時遇到問題。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>"> 

回答

1

我能夠從查詢字符串中刪除括號來解決語法錯誤。

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

應該

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