I created a table called participant composed by participant_ID (which is the primary key and is identity[has an auto-value]) and session_ID (which is a foreign key).
When I create a new participant, I would like to store its participant_ID.
I have the following code, but I get the following message error: 'Syntax problem near returning'
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')
Many thanks in advance!
To get an ID of last inserted record, you can use this T-SQL: INSERT INTO Persons (FirstName) VALUES ('Joe'); SELECT ID AS LastID FROM Persons WHERE ID = @@Identity; You can use query like this inside stored procedure or as an ad-hoc query.
If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL. Insert some records in the table using insert command. Display all records from the table using select statement.
IDENT_CURRENT() will give you the last identity value inserted into a specific table from any scope, by any user. @@IDENTITY gives you the last identity value generated by the most recent INSERT statement for the current connection, regardless of table or scope.
This is a really, really old post, I know - but I had the same question and came upon it. I got mine working and thought I would share for those that stumble here as I have. Please be kind, this was my first pass at the code. It isn't pretty, but it should get you started.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With