SQL 服务器:从 python 调用时存储过程不工作
SQL Server: stored procedure not working when called from python
我有一个名为 Points
的简单 table,有两列 QuestionID
和 UserID
:
QuestionID UserID
-------------------
5 2
6 1
我写了一个存储过程来插入数据到这个table:
CREATE PROCEDURE [dbo].[SetPoints]
@QuestionID INT,
@UserID INT
AS
INSERT INTO dbo.Points (QuestionID, UserID)
VALUES (@QuestionID, @UserID)
我执行了这个程序,它似乎工作正常。
然后我写了 Python 代码来连接到这个数据库并执行这个程序。
import pyodbc as po
# Connection variables
server = '################'
database = '#############'
username = '#############'
password = '################'
# Connection string
cnxn = po.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' +
server+';DATABASE='+database+';UID='+username+';PWD=' + password)
cursor = cnxn.cursor()
# Prepare the stored procedure execution script and parameter values
storedProc = "EXEC SetPoints @QuestionID = ?, @UserID = ?"
params = (2, 3)
# Execute stored procedure with parameters
cursor.execute(storedProc, params)
# Close the cursor and delete it
cursor.close()
del cursor
# Close the database connection
cnxn.close()
当我 运行 Execute
Python 代码显示没有错误,但如果我检查 Points
table,则没有插入任何内容.. ..
有人能告诉我这是怎么回事吗?该过程在 SSMS 中运行良好,但当我从 Python 执行它时,没有任何反应。
解决方案:
解决方案是将 auto_commit=True
添加到 pyodbc.connect()
函数。
我在这个网站上找到了另一个 post 的答案。
我有一个名为 Points
的简单 table,有两列 QuestionID
和 UserID
:
QuestionID UserID
-------------------
5 2
6 1
我写了一个存储过程来插入数据到这个table:
CREATE PROCEDURE [dbo].[SetPoints]
@QuestionID INT,
@UserID INT
AS
INSERT INTO dbo.Points (QuestionID, UserID)
VALUES (@QuestionID, @UserID)
我执行了这个程序,它似乎工作正常。
然后我写了 Python 代码来连接到这个数据库并执行这个程序。
import pyodbc as po
# Connection variables
server = '################'
database = '#############'
username = '#############'
password = '################'
# Connection string
cnxn = po.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' +
server+';DATABASE='+database+';UID='+username+';PWD=' + password)
cursor = cnxn.cursor()
# Prepare the stored procedure execution script and parameter values
storedProc = "EXEC SetPoints @QuestionID = ?, @UserID = ?"
params = (2, 3)
# Execute stored procedure with parameters
cursor.execute(storedProc, params)
# Close the cursor and delete it
cursor.close()
del cursor
# Close the database connection
cnxn.close()
当我 运行 Execute
Python 代码显示没有错误,但如果我检查 Points
table,则没有插入任何内容.. ..
有人能告诉我这是怎么回事吗?该过程在 SSMS 中运行良好,但当我从 Python 执行它时,没有任何反应。
解决方案:
解决方案是将 auto_commit=True
添加到 pyodbc.connect()
函数。
我在这个网站上找到了另一个 post 的答案。