简体   繁体   中英

Python: Execute Stored Procedure with Parameters

I'm working on a Python script that writes records from a stored procedure to a text file. I'm having issues executing the stored procedure with parameters.

I'm not sure what I could do differently to execute this stored procedure with both parameters. You can see the error I'm getting below.

Any insight would be appreciated.

Here's my code

# 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()

Here's the error

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>">

I was able to fix the syntax error by removing the parenthesis from the query string.

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

should be

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

This worked for me

query = "EXEC [store_proc_name] @param1='param1', @param2= 'param2'"
cursor.execute(query)

对于 SQL Server:

cursor.execute('{call your_sp (?)}',var_name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM