【问题标题】:How to get the IDENTITY value when using INSERT ... OUTPUT with pyodbc使用 INSERT ... OUTPUT 和 pyodbc 时如何获取 IDENTITY 值
【发布时间】:2017-11-08 20:24:04
【问题描述】:

我正在尝试使用OUTPUT 获取新插入行的 ID。但是,我遇到了 HY010 错误。以下查询/代码是我使用的:

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)')

【问题讨论】:

  • 您是否尝试过只执行插入然后访问cursor.lastrowidpython.org/dev/peps/pep-0249/#lastrowid
  • 我收到一条错误消息AttributeError: pyodbc.Cursor object has no attribute lastrowid.

标签: python sql-server pyodbc


【解决方案1】:

我能够重现您的问题,并且可以通过在 INSERT 之后和提交之前 立即检索 id 值来避免它。也就是说,而不是

cursor.execute(string, "John Doe", 35)
cursor.commit()
id = cursor.fetchone()[0]

我做到了

cursor.execute(string, "John Doe", 35)
id = cursor.fetchone()[0]  # although cursor.fetchval() would be preferred
cursor.commit()

【讨论】:

    【解决方案2】:

    对我来说,这仅适用于 Azure SQL Serverless(使用 pyodbc==4.0.28):

    cursor.execute(insert_statement, param_value_list)
    cursor.execute("SELECT @@IDENTITY AS ID;")
    return cursor.fetchone()[0]
    

    【讨论】:

      【解决方案3】:

      如果您使用带有engine 的 SQLAlchemy,那么您可以在运行查询和获取表 ID 之前像这样检索 PyODBC 游标。

          connection = sql_alchemy_engine.raw_connection()
          cursor = connection.cursor()
          result = cursor.execute(
              """
              INSERT INTO MySchema.MyTable (Col1, Col2) OUTPUT INSERTED.MyTableId 
              VALUES (?, ?);
              """,
              col1_value,
              col2_value,
          )
          myTableId = cursor.fetchone()[0]
          cursor.commit()
          print("my ID is:", myTableId)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-19
        • 1970-01-01
        相关资源
        最近更新 更多