Skip to content Skip to sidebar Skip to footer

How To Get Id Of Last Inserted Row By Qsqlquery.lastinsertid() From Sql Server?

How can I get ID of last inserted row from SQL Server by PyQt4.QtSql module? Now I'm using SQL Server 2012 Express, but program has to work also on SQL Server 2000. Here is my code

Solution 1:

Moving my comment to an answer to allow this to be closed cleanly:

I don't know Python, but I think SCOPE_IDENTITY() only works within a batch. So, you might want to add the ;SELECT SCOPE_IDENTITY() to the query with the INSERT. Hope this helps.

So your Insert could look like:

query = QtSql.QSqlQuery() 
query.prepare('INSERT Test VALUES(?); SELECT SCOPE_IDENTITY()') 
query.bindValue(0, 'Test') 

query.exec_() 

while query.next(): 
    last_inserted_id = query.value(0) 

Solution 2:

QSqlQuery Class has a method lastInsertId which returns the id of the last inserted row.

query = QtSql.QSqlQuery() 
query.exec_('INSERT Test (id, name) VALUES(1, 'Test')')

# Get the ID of the last inserted row
query.lastInsertId() # Output : 1

Post a Comment for "How To Get Id Of Last Inserted Row By Qsqlquery.lastinsertid() From Sql Server?"