Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>">
like image 200
localhost Avatar asked Jun 25 '26 19:06

localhost


1 Answers

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'"
like image 97
localhost Avatar answered Jun 27 '26 09:06

localhost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!