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 (Python + PyQt) and results:
from PyQt4.QtGui import QApplication
from PyQt4 import QtSql
app = QApplication([])
db = QtSql.QSqlDatabase.addDatabase("QODBC")
db.setDatabaseName('Driver={SQL Server Native Client 11.0};Server=(localdb)\\v11.0;')
db.open()
query = QtSql.QSqlQuery()
query.prepare("""CREATE TABLE Test(
ID INT PRIMARY KEY IDENTITY(1, 1),
Row nvarchar(255)
)
""")
query.exec_()
query = QtSql.QSqlQuery()
query.prepare('INSERT Test OUTPUT Inserted.ID VALUES(?)')
query.bindValue(0, 'Test')
query.exec_()
while query.next():
last_inserted_id = query.value(0)
print('OUTPUT: ', last_inserted_id)
print('QSqlQuery.lastInsertId: ', query.lastInsertId())
query = QtSql.QSqlQuery('SELECT SCOPE_IDENTITY()')
while query.next():
last_inserted_id_ = query.value(0)
print('SCOPE_IDENTITY: ', last_inserted_id_)
db.close()
Results:
OUTPUT: 1
QSqlQuery.lastInsertId: None
SCOPE_IDENTITY: <PyQt4.QtCore.QPyNullVariant object at 0x00000000032D88D0>
Unfortunately OUTPUT Clause is supported by SQL Server 2005 or above.
Python 3.2.3 (x64), PyQt 4.9.4, SQL Server 2012 Express
Any ideas?
Edit:
So far I use SELECT @@IDENTITY.
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: