python pyodbc:在 conn.commit() 之前关闭光标?
我在使用 python 包 pyodbc 将数据插入数据库时遇到问题,因为我对 pyodbc 还很陌生。一般来说,我可能缺乏一些基本的了解。
我打开一个连接,然后我想要执行我的查询。 实际上,在这个查询中我调用了一个存储过程(它不是我编写的,也不允许我更改!)。 此过程执行“一两次”插入。当我像这样使用 pyodbc 时
conn = pyodbc.connect(connection_string)
with conn:
c = conn.cursor()
c.execute("{call input_procedure('some','parameters','to','insert')}")
,或者
conn = pyodbc.connect(connection_string)
c = conn.cursor()
c.execute("{call input_procedure('some','parameters','to','insert')}")
conn.commit()
收到以下错误消息: pyodbc.Error: ('HY000', "[HY000] [MySQL][ODBC 8.0(a) Driver]命令不同步;您现在无法运行此命令 (2014) (SQLEndTran(SQL_COMMIT))" )
据我了解,此错误消息可能是由于在被调用的过程中执行了多个插入造成的。当我打印执行命令的返回时,我变成以下内容: (' ', )
当我在提交之前关闭游标时,一切正常。就像这样:
conn = pyodbc.connect(connection_string)
c = conn.cursor()
c.execute("{call input_procedure('some','parameters','to','insert')}")
c.close()
conn.commit()
我真的不明白这里发生了什么。 这种行为有解释吗?是否在提交保存之前关闭游标?
非常感谢您的帮助!
I have an issue with inserting data into a database using the python package pyodbc and since I am pretty new to pyodbc & databases in general, I might lack some basic understanding.
I open a connection, and then I want the execute my query.
Actually, in this query I call a stored procedure (which I didn't write and I am not allowed to change!).
This procedure does "one or two" inserts. When I use pyodbc like this
conn = pyodbc.connect(connection_string)
with conn:
c = conn.cursor()
c.execute("{call input_procedure('some','parameters','to','insert')}")
OR
conn = pyodbc.connect(connection_string)
c = conn.cursor()
c.execute("{call input_procedure('some','parameters','to','insert')}")
conn.commit()
I get the following error message:pyodbc.Error: ('HY000', "[HY000] [MySQL][ODBC 8.0(a) Driver]Commands out of sync; you can't run this command now (2014) (SQLEndTran(SQL_COMMIT))")
As far as I understood, this error message might be due to executing more than one insert within the called procedure. When I print the return of the execute command I become the following: (' ', )
When I instead close the cursor, before doing the commit, everything works fine. Like this:
conn = pyodbc.connect(connection_string)
c = conn.cursor()
c.execute("{call input_procedure('some','parameters','to','insert')}")
c.close()
conn.commit()
I really don't understand what's happening here.
Is there an explanation for this behaviour? Is closing the cursor before doing the commit save?
Thanks a lot for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您似乎在 MySQL Connector/ODBC 处理存储过程结果集时遇到了一个怪癖。对于此示例过程:
此 Python 代码
引发“命令不同步”错误,而此代码则
不会。
You seem to have encountered a quirk in MySQL Connector/ODBC's handling of result sets from a stored procedure. For this example procedure:
this Python code
throws the "Commands out of sync" error, whereas this code
does not.