insert statements get id #1162
-
Hello, I wanted to ask if it's possible to get the id of a row after inserting without doing a select after? I couldn't find anything in the docs. Also, keywords for other users who might search this topic: |
Beta Was this translation helpful? Give feedback.
Answered by
gordthompson
Feb 7, 2023
Replies: 1 comment 2 replies
-
If your DBMS supports an 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 |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
gordthompson
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If your DBMS supports an
OUTPUT
clause (or similar) for DML then you can use that. For example, with MS SQL Server: