Python:执行带参数的存储过程 [英] Python: Execute Stored Procedure with Parameters

查看:76
本文介绍了Python:执行带参数的存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

任何见解将不胜感激.

这是我的代码

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

推荐答案

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

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

应该

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

这篇关于Python:执行带参数的存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆