【问题标题】:is there a way to do a insert an request the scope_identity() using pyodbc to sql server 2005有没有办法使用 pyodbc 向 sql server 2005 插入请求 scope_identity()
【发布时间】: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


【解决方案1】:

试试这个,一个带有OUTPUT 子句的语句

cur = con.execute(
         "insert into sometable OUTPUT INSERTED.idcolumn values('something')"
         )

编辑:这应该可以解决 Joe S 评论的问题。

【讨论】:

  • 如何打印出cur中的值?
【解决方案2】:

使用SCOPE_IDENTITY() 是可行的方法,因为使用 OUTPUT 和 @@IDENTITY 存在限制和怪癖,因为触发器。

使用您的代码剪切,您只需添加对nextset 的调用即可获取ID。

...
con = pyodbc.connect('conectionString', autocommit = True)
cur = con.execute(
                  "insert into sometable values('something');
                  select scope_identity() as id"
                  )
cur.nextset()
for id in cur:
   print id
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多