【问题标题】:How to get the last created ID in SQL如何在 SQL 中获取最后创建的 ID
【发布时间】:2013-10-15 10:07:43
【问题描述】:

我创建了一个名为参与者的表,由参与者ID(主键,身份[具有自动值])和会话ID(外键)组成。

当我创建一个新参与者时,我想存储它的参与者 ID。

我有以下代码,但收到以下消息错误:“返回附近的语法问题”

connection = pyodbc.connect('Driver={SQL Server Native Client 11.0};Serve=:xxx;Database=xxx;Uid=xxx;Pwd=xxx')
cur = connection.cursor()
pID = cur.execute('INSERT INTO participant(sessions_ID) VALUES (40) RETURNING participant_ID')

提前非常感谢!

【问题讨论】:

标签: python sql sql-server pyodbc


【解决方案1】:

这是一个非常非常老的帖子,我知道 - 但我有同样的问题并遇到了它。我开始工作了,我想我会为那些像我一样在这里绊倒的人分享。请善待,这是我第一次通过代码。它不漂亮,但它应该让你开始。

def exec_query(self, query_type, query):
    # query_type: This is an enumumeration defining the CRUD operation of the query.

    # Note, the native client (11.0) might change with time and Windows updates)
    # Note, the driver varlue would normally go in a constant, I put it here just for clarity
    with pypyodbc.connect('DRIVER={SQL Server Native Client 11.0}; ' + self.cnx_str) as connection:
        cursor = connection.cursor()
        cursor.execute(query)

        if query_type is QueryType.create:
            try:
                cursor.execute("SELECT SCOPE_IDENTITY()")
                row = cursor.fetchone()
                seed_id = row[0]
            except AttributeError:
                seed_id = 0
            cursor.commit()
            return seed_id

        # ... Additional code for non 'create' operations

【讨论】:

  • 这个答案的问题是它没有解释query_typeQueryType来自哪里。
  • @DataHerder;我可以看到这可能会令人困惑——它只是我创建的一个枚举,用于传递给我的方法。可以忽略,重要的是create'if'语句里面的代码。
  • 我有这个错误没有结果。以前的 SQL 不是查询。我正在使用存储过程。如何获取 id 身份
【解决方案2】:

你可以通过两种方式做到这一点

  1. select SCOPE_IDENTITY() - 这是首选,因为它受限于您创建的身份的范围。

  2. select @@IDENTITY - 这是创建的最后一个身份,与范围无关(例如,触发器可以创建其他身份)。

在这里查看更多信息:http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/

【讨论】:

  • I WROTE pID = cur.execute("SEELECT @@Identity") 在上一个查询之后,但我得到以下信息: ...我怎么能得到ID 的值?
  • 你有双EE在select吗?
  • 你的表有Identity列吗?
【解决方案3】:

请在插入查询后尝试SELECT @@Identity,这将返回当前连接的主键标识列值。

【讨论】:

  • I WROTE pID = cur.execute("SELECT @@Identity") 在上一个查询之后,但我得到以下信息:
  • 你必须附加“.fetchone()”
  • 我必须添加 [0] 并将其设置为 int int(self.dbcon.execute("SELECT @@IDENTITY as id").fetchone()[0])
  • 您可以根据您的数据库字段数据类型将其转换为 Int 或 long 以匹配您的代码变量类型
猜你喜欢
  • 1970-01-01
  • 2013-12-09
  • 2019-10-26
  • 2021-11-08
  • 2011-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-04
相关资源
最近更新 更多