string = """
SET NOCOUNT ON;
DECLARE @NEWID TABLE(ID INT);
INSERT INTO dbo.t1 (Username, Age)
OUTPUT inserted.id INTO @NEWID(ID)
VALUES(?, ?)
SELECT ID FROM @NEWID
"""
cursor.execute(string, "John Doe", 35)
cursor.commit()
id = cursor.fetchone()[0]
最后一行
id = cursor.fetchone()[0]
导致HY010错误(见下文)。任何建议将不胜感激!
pyodbc.Error: ('HY010', '[HY010] [Microsoft][ODBC SQL Server Driver]Function sequence error (0) (SQLFetch)')
对于我来说,这仅适用于Azure SQL Serverless(使用
Pyodbc==4.0.28):
cursor.execute(insert_statement, param_value_list)
cursor.execute("SELECT @@IDENTITY AS ID;")
return cursor.fetchone()[0]
我能够复制您的问题,我能够通过在插入后立即检索
id
值,并在插入后wede the the commit。也就是说,而不是
我做了
cursor.execute(string, "John Doe", 35)
id = cursor.fetchone()[0] # although cursor.fetchval() would be preferred
cursor.commit()
如果您使用的是sqlalchemy,则可以在运行查询并获取表ID之前像这样检索pyodbc光标。
engine
对于其他正在谷歌搜索如何找到最新自动生成的ID的人,但由于某种原因,它使用Azure SQL不起作用或返回不像我那样返回。使其自动生成ID然后检索它的替代解决方案是在Python中使用UUID模块(Https://docs.python.org/3/library/uuid.html,然后用它插入。
给定的答案对我有用,与SQL Express在Local和PyodBC上,我只想强调一些使我避免的事情(因为我对C#和EF很熟悉): 我一开始忘记了:
import uuid
row_id = uuid.uuid4()
cursor.execute(f"INSERT INTO Person(ID,name) VALUES ({row_id}, 'Graham Smith')")
在SQL子句中,必须获得身份结果。