Recent

Author Topic: Select last insert row id  (Read 475 times)

LemonParty

  • Sr. Member
  • ****
  • Posts: 393
Select last insert row id
« on: November 05, 2025, 05:41:20 pm »
I have this code:
Code: Pascal  [Select][+][-]
  1. function TdmSQLite.Insert(Path: String; Archive: TByteDynArray): SizeInt;
  2. begin
  3.   Result:= -1;
  4.   Query.Close;
  5.   Query.SQL.Text:= 'INSERT INTO Backup(Path, Archive) VALUES (:Path, :Archive)';
  6.   Query.ParamByName('Path').AsString:= Path;
  7.   Query.ParamByName('Archive').AsBlob:= Archive;
  8.   Query.ExecSQL;
  9.   Tran.Commit;
  10.  
  11.   Query.SQL.Text:= 'SELECT last_insert_rowid()';
  12.   Query.Open;
  13.   Result:= Query.Fields[0].AsInteger;
  14. end;

And I have a doubt. Should I put Transaction.Commit after or before "SELECT last_insert_rowid()"?
Lazarus v. 4.99. FPC v. 3.3.1. Windows 11

Sieben

  • Sr. Member
  • ****
  • Posts: 384
Re: Select last insert row id
« Reply #1 on: November 05, 2025, 06:30:03 pm »
Before - insert action has to be finalized to produce a valid ID. And you might as well use TSQLite3Connection.GetInsertID instead of your Query.
Lazarus 2.2.0, FPC 3.2.2, .deb install on Ubuntu Xenial 32 / Gtk2 / Unity7

LemonParty

  • Sr. Member
  • ****
  • Posts: 393
Re: Select last insert row id
« Reply #2 on: November 05, 2025, 06:37:52 pm »
Thank you.
Lazarus v. 4.99. FPC v. 3.3.1. Windows 11

Zvoni

  • Hero Member
  • *****
  • Posts: 3230
Re: Select last insert row id
« Reply #3 on: November 05, 2025, 06:58:40 pm »
Or implement a Callback like described here: http://sqlite.org/c3ref/update_hook.html
The it's basically like an Event
One System to rule them all, One Code to find them,
One IDE to bring them all, and to the Framework bind them,
in the Land of Redmond, where the Windows lie
---------------------------------------------------------------------
Code is like a joke: If you have to explain it, it's bad

 

TinyPortal © 2005-2018