Python:使用参数执行存储过程

时间:2015-12-11 16:27:28

标签: python sql-server stored-procedures

我正在使用Python脚本将记录从存储过程写入文本文件。我在使用参数执行存储过程时遇到问题。

我不确定用两个参数执行此存储过程可以做些什么。你可以看到我在下面的错误。

任何见解都将受到赞赏。

这是我的代码

<div class="field">
    <%= f.label :image %><br>
    <%= f.file_field :image%>
</div>

这是错误

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

3 个答案:

答案 0 :(得分:1)

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

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

应该是

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

答案 1 :(得分:0)

这对我有用

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

答案 2 :(得分:0)

对于SQL Server:

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