Pyodbc:成功插入SQL Server数据库后如何获取主键?

iam*_*mdi 1 python sql-server pyodbc

我在 SQL Server 中有一个表Employee如下:

ID (AUTO, PK),
firstname (varchar),
lastname (varchar)
Run Code Online (Sandbox Code Playgroud)

我想将数据插入('John', 'Myers')表中。

我使用 pyodbc 在 Python 中使用了以下代码:

connection = pyodbc.connect(...)
cursor = connection.cursor()
cursor.execute("insert into employee(firstname, lastname) values(?, ?)", ['John','Myers'])
Run Code Online (Sandbox Code Playgroud)

是否可以ID在无需编写select查询的情况下获取新插入的行的值?

Cha*_*ace 5

您可以使用该OUTPUT子句

cursor.execute("insert into employee(firstname, lastname) output inserted.ID values(?, ?);", ['John','Myers'])
id = cursor.fetchone()
Run Code Online (Sandbox Code Playgroud)

或者,使用SCOPE_IDENTITY()

cursor.execute("insert into employee(firstname, lastname) values(?, ?); select SCOPE_IDENTITY();", ['John','Myers'])
id = cursor.fetchone()
Run Code Online (Sandbox Code Playgroud)