Skip to content

insert statements get id #1162

Answered by gordthompson
woif00 asked this question in Q&A
Feb 7, 2023 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

If your DBMS supports an OUTPUT clause (or similar) for DML then you can use that. For example, with MS SQL Server:

import pyodbc

cnxn = pyodbc.connect(
    "DSN=mssql_199;UID=scott;PWD=tiger^5HHH", autocommit=True
)
crsr = cnxn.cursor()

table_name = "discussion_1162"
crsr.execute(f"DROP TABLE IF EXISTS {table_name}")
crsr.execute(
    f"CREATE TABLE {table_name} (id int identity primary key, txt varchar(50))"
)

sql = f"""\
INSERT INTO {table_name} (txt) OUTPUT inserted.id VALUES (?)
"""
new_id = crsr.execute(sql, "foo").fetchval()
print(new_id)  # 1
new_id = crsr.execute(sql, "bar").fetchval()
print(new_id)  # 2

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@MulleOne
Comment options

@BoBThegrEat297
Comment options

Answer selected by gordthompson
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants