Recent

Author Topic: How to get last inserted id after insert  (Read 1276 times)

Gebo

  • Jr. Member
  • **
  • Posts: 67
    • chahpander for lingeries
How to get last inserted id after insert
« on: December 28, 2025, 12:34:06 pm »
I insert invoice data in sale_invoice table, then I need the id value to insert the sold product to sold_items with invoiceid.
How to get last inserted id after insert the invoice data?

I use zeosdb and mariadb. 
I like programming I begun by vb,vb.net,c# and finally free pascal and lazarus .I like martial arts sports and I am a kickboxer and made our team sport club called black eagle school I have a website for modern clothes..

egsuh

  • Hero Member
  • *****
  • Posts: 1738
Re: How to get last inserted id after insert
« Reply #1 on: December 28, 2025, 02:08:40 pm »
I would define afterinsert event handler.

dseligo

  • Hero Member
  • *****
  • Posts: 1653
Re: How to get last inserted id after insert
« Reply #2 on: December 28, 2025, 02:42:27 pm »
Like this:
Code: Pascal  [Select][+][-]
  1. With ZQuery do
  2. begin
  3.   SQL.Text := 'insert into sale_invoice (field1, field2, ...) values ' +
  4.     '(:field1, :field2, ...)';
  5.   ParamByName('field1').AsInteger := 12323;
  6.   ParamByName('field2').AsString := '12323';
  7.   ...
  8.   ExecSQL;
  9.  
  10.   SQL.Text:='select LAST_INSERT_ID()';
  11.   Open;
  12.   iLastID := Fields[0].AsInteger;
  13.   ...
  14. end;

P.S.: And if you insert from another table, you can also do it like this, without variable:
Code: Pascal  [Select][+][-]
  1. SQL.Text := 'insert into sold_items ' +
  2.   '(itemid, field1, field2, ...) ' +
  3.   'select last_insert_id(), field1, field2, ... ' +
  4.   'from someothertable ' +
  5.   'where ...';
  6. ParamByName('...').AsString := 'abc';
  7. ExecSQL;
« Last Edit: December 28, 2025, 03:06:57 pm by dseligo »

Nimbus

  • Jr. Member
  • **
  • Posts: 84

Gebo

  • Jr. Member
  • **
  • Posts: 67
    • chahpander for lingeries
Re: How to get last inserted id after insert
« Reply #4 on: December 28, 2025, 05:28:28 pm »
I tried
Code: Pascal  [Select][+][-]
  1. ascal  [Select]
  2. [+]
  3.  
  4.     With ZQuery do
  5.     begin
  6.       SQL.Text := 'insert into sale_invoice (field1, field2, ...) values ' +
  7.         '(:field1, :field2, ...)';
  8.       ParamByName('field1').AsInteger := 12323;
  9.       ParamByName('field2').AsString := '12323';
  10.       ...
  11.       ExecSQL;
  12.      
  13.       SQL.Text:='select LAST_INSERT_ID()';
  14.       Open;
  15.       iLastID := Fields[0].AsInteger;
  16.       ...
  17.     end;
  18.  
but It returns 0.
I like programming I begun by vb,vb.net,c# and finally free pascal and lazarus .I like martial arts sports and I am a kickboxer and made our team sport club called black eagle school I have a website for modern clothes..

jcmontherock

  • Sr. Member
  • ****
  • Posts: 336
Re: How to get last inserted id after insert
« Reply #5 on: December 28, 2025, 05:48:56 pm »
Maybe a "commit" after insert was missing.
Windows 11 UTF8-64 - Lazarus 4.4-64 - FPC 3.2.2

dseligo

  • Hero Member
  • *****
  • Posts: 1653
Re: How to get last inserted id after insert
« Reply #6 on: December 28, 2025, 06:41:22 pm »
Maybe a "commit" after insert was missing.

Either that or his table doesn't have AUTO_INCREMENT column.

jcmontherock

  • Sr. Member
  • ****
  • Posts: 336
Re: How to get last inserted id after insert
« Reply #7 on: December 29, 2025, 06:14:37 pm »
Did you check if your table was updated after insert ?
Windows 11 UTF8-64 - Lazarus 4.4-64 - FPC 3.2.2

egsuh

  • Hero Member
  • *****
  • Posts: 1738
Re: How to get last inserted id after insert
« Reply #8 on: December 30, 2025, 09:30:03 am »
Commit update shouldn’t matter as within the same transaction.

swissbob

  • Newbie
  • Posts: 5
Re: How to get last inserted id after insert
« Reply #9 on: December 30, 2025, 05:50:51 pm »
I insert invoice data in sale_invoice table, then I need the id value to insert the sold product to sold_items with invoiceid.
How to get last inserted id after insert the invoice data?

I use zeosdb and mariadb.

Well in a properly designed database, the auto inc field should be a candidate key used for fast loading of records, so you should use that actual primary key to return it.

Failing that would be best to use an insert/return statement...

And the least preferred option is to query the last used id.  But in environments with a high degree of concurrency managed by professionals,  that may occasionally fail I have seen it in banking and the travel industry.  But it is probably good enough in most cases.

Gebo

  • Jr. Member
  • **
  • Posts: 67
    • chahpander for lingeries
Re: How to get last inserted id after insert
« Reply #10 on: December 31, 2025, 11:03:07 am »
Did you check if your table was updated after insert ?
yes the invoice is saved in the table.
I can't make the code in one transaction and I don't know why.

my code is
Code: Pascal  [Select][+][-]
  1. ZConnection3.Connect;
  2.   ZConnection3.StartTransaction;
  3.   //إدخال بيانات الفاتورة وجلب ID الفاتورة
  4.   ZQuery3.Close;
  5.   ZQuery3.SQL.Clear;
  6.   ZQuery3.SQL.Text:='insert into sales_invoices (invoice_date,customer_id,total)values(:indate,:custid, :total)';
  7.   ZQuery3.ParamByName('custid').AsInteger:= VarAsType(DBLookupComboBox1.KeyValue, varInteger);
  8.   ZQuery3.ParamByName('total').AsFloat:=total;
  9.   ZQuery3.ParamByName('indate').AsDate:=Date;
  10.   ZQuery3.ExecSQL;
  11.  
  12.   ZQuery3.SQL.Text:='SELECT LAST_INSERT_ID()';
  13.   ZQuery3.Open;
  14.  
  15.   invoiceid:=ZQuery3.Fields[0].AsInteger;
  16.  
  17.   ZQuery3.Close;
  18.  
  19.   if invoiceid=0 then
  20.     raise Exception.Create('لم يتم تسجيل الفاتورة');
  21.   //تسجيل عناصر الفاتورة
  22.   ZMemTable1.First;
  23.  
  24.   ZQuery3.Close;
  25.   ZQuery3.SQL.Clear;
  26.   ZQuery3.SQL.Text:='insert into sales_items(invoice_id,item,qty,sale_price,cost_price,total_price)values(:inid,:it,:qty,:saleprice,:costprice,:total)';
  27.   while not ZMemTable1.EOF do
  28.   begin
  29.     ZQuery3.ParamByName('inid').AsInteger:=invoiceid;
  30.     ZQuery3.ParamByName('it').AsString:=ZMemTable1.FieldByName('productname').AsString;
  31.     ZQuery3.ParamByName('qty').AsFloat:=ZMemTable1.FieldByName('qty').AsFloat;
  32.     ZQuery3.ParamByName('saleprice').AsFloat:=ZMemTable1.FieldByName('price').AsFloat;
  33.     ZQuery3.ParamByName('costprice').AsFloat:=ZMemTable1.FieldByName('costprice').AsFloat;
  34.     ZQuery3.ParamByName('total').AsFloat:=ZMemTable1.FieldByName('total').AsFloat;
  35.     ZQuery3.ExecSQL;
  36.     ZMemTable1.Next;
  37.   end;
  38.   ZConnection3.Commit;
  39.   ShowMessage('تم حفظ الفاتورة رقم '+IntToStr(invoiceid)+' بنجاح');
  40.  
  41.  
  42.   Except on e:Exception do
  43.   begin
  44.     if ZConnection3.InTransaction then ZConnection3.Rollback;;
  45.     MessageDlg('خطأ أثناء حفظ الفاتورة:' + LineEnding +E.Message,mtError, [mbOK],0);
  46.   end;
  47.   end;
  48.  
I like programming I begun by vb,vb.net,c# and finally free pascal and lazarus .I like martial arts sports and I am a kickboxer and made our team sport club called black eagle school I have a website for modern clothes..

zeljko

  • Hero Member
  • *****
  • Posts: 1826
    • http://wiki.lazarus.freepascal.org/User:Zeljan
Re: How to get last inserted id after insert
« Reply #11 on: December 31, 2025, 12:37:03 pm »
mariadb/mysql does not have RETURNING ? eg insert into mytable .....etc RETURNING recno; (eg recno is serial) and then after Open just read FieldByName('recno').AsInteger ? I'm using it in postgresql.

Gebo

  • Jr. Member
  • **
  • Posts: 67
    • chahpander for lingeries
Re: How to get last inserted id after insert
« Reply #12 on: December 31, 2025, 01:56:32 pm »
mariadb/mysql does not have RETURNING ? eg insert into mytable .....etc RETURNING recno; (eg recno is serial) and then after Open just read FieldByName('recno').AsInteger ? I'm using it in postgresql.

I want the invoice to be cancelled if a problem has happened with sales items. I want it to be one transaction.
I like programming I begun by vb,vb.net,c# and finally free pascal and lazarus .I like martial arts sports and I am a kickboxer and made our team sport club called black eagle school I have a website for modern clothes..

cdbc

  • Hero Member
  • *****
  • Posts: 2600
    • http://www.cdbc.dk
Re: How to get last inserted id after insert
« Reply #13 on: December 31, 2025, 02:25:36 pm »
Hi
LMGTFY  >:(
Quote
LAST_INSERT_ID() (no arguments) returns the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement. The value of LAST_INSERT_ID() remains unchanged if no rows are successfully inserted
found HERE
Regards Benny
« Last Edit: December 31, 2025, 02:27:25 pm by cdbc »
If it ain't broke, don't fix it ;)
PCLinuxOS(rolling release) 64bit -> KDE6/QT6 -> FPC Release -> Lazarus Release &  FPC Main -> Lazarus Main

jcmontherock

  • Sr. Member
  • ****
  • Posts: 336
Re: How to get last inserted id after insert
« Reply #14 on: December 31, 2025, 05:00:12 pm »
Yes, I forgot that in Mariadb and Mysql an AUTO-INCREMENT field is not implicit and defined by default. It is with SQLite. Sorry.
Windows 11 UTF8-64 - Lazarus 4.4-64 - FPC 3.2.2

 

TinyPortal © 2005-2018