Page 1 of 1

Last inserted RowID

Posted: Mon 01 Oct 2012 22:43
by FHannes
I've got a TLiteQuery object which I'm using to insert a row into my database. The SQL property contains the INSERT statement which is postfixed by "; SELECT LAST_INSERT_ROWID() AS rowid". After binding my params and macros I execute it like this:

Code: Select all

    Query.Open;
    if Query.FindFirst then
      Result := Query.FieldByName('rowid').AsLargeInt;
    Query.Close;
The issue I'm experiencing is that I get an error from the operation that the query does not return any rows. The INSERT statement is executed successfully however. I'm using the direct mode.

Re: Last inserted RowID

Posted: Tue 02 Oct 2012 08:58
by ZEuS
The TLiteQuery component is intended to execute a single SQL-statement, not a list of statements. So, when trying to execute a complex statement, which consists of an "INSERT ..." followed by a "; SELECT ...", then the second part of the statement is ignored.
To be able to retrieve a LAST_INSERT_ROWID() value, you should change your code like the following:

Code: Select all

 Query.SQL.Text := 'INSERT INTO ...';
 Query.Execute;
 Query.SQL.Text := 'SELECT LAST_INSERT_ROWID() AS rowid';
 Query.Open;
 if Query.FindFirst then
   Result := Query.FieldByName('rowid').AsLargeInt;
 Query.Close; 

Re: Last inserted RowID

Posted: Tue 02 Oct 2012 17:42
by FHannes
Thank you, that resolved the issue.