【发布时间】:2010-12-23 18:54:50
【问题描述】:
我有这个很棒的 pyodbc 库。我尝试下面的代码,它应该插入一行并返回行 ID,但它不起作用。顺便说一句,我在服务器上使用 sql server 2005,客户端是 windows os
...
con = pyodbc.connect('conectionString', autocommit = True)
cur = con.execute(
"insert into sometable values('something');
select scope_identity() as id"
)
for id in cur:
print id
...
有什么想法吗?
【问题讨论】:
-
Per this FAQs page: "Use "SELECT @@IDENTITY"。请注意@@IDENTITY 返回最后生成的值,因此如果触发器导致第二次插入,您将获得触发器生成的值. SQL Server 还提供了 SCOPE_IDENTITY() 来解决这个问题。不幸的是,SQL Server ODBC 驱动程序为每个执行调用调用一个内部存储过程,这会弄乱范围,使其无法使用。"
标签: python sql-server pyodbc