Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyodbc on SQL Server - How can I do an insert and get the row ID back?

I'm using pyodbc with SQL Server 2000.

I want to be able to insert a row and get the auto incremented row id value back? Any ideas?

Here's what I have so far:

cursor.execute("insert into products(id, name) values ('pyodbc', 'awesome library')")
cnxn.commit()
like image 961
Greg Avatar asked May 21 '10 16:05

Greg


People also ask

How do you get ID of the newly inserted record in a database?

@@IDENTITY returns the id of the last thing that was inserted by your client's connection to the database. IDENT_CURRENT returns the last ID that was inserted by anyone. If some other app happens to insert another row at an unforunate time, you'll get the ID of that row instead of your one.

How can I get current insert ID in SQL?

The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.

What does pyodbc connect return?

Returns a new Cursor Object using the connection. pyodbc supports multiple cursors per connection but your database may not.


1 Answers

Sorry, I asked too soon, it's addressed in their FAQ

Use "SELECT @@IDENTITY".

like image 174
Greg Avatar answered Oct 19 '22 00:10

Greg