Hi,

first of all I am new to using Lazarus/FPC for database communication.
I have set up my database connection, transaction and queries via the Object 
Inspector and all is working as it should. But I have a little problem getting 
the PK value of a newly inserted record (the PK field is an auto-incremented 
one).
Actually it's not really a problem, I just don't like the way I do it and found 
no better one.

Here is some code:

SQLQuery.Insert;
SQLQuery.FieldByName('SomeField').AsString:=SomeValue;
SQLQuery.FieldByName('AnotherField').AsString:=AnotherValue;
... (setting more fields)
SQLQuery.Post;
SQLQuery.ApplyUpdates;
SQLTransaction.Commit;
// Now the part I don't like
SQLQuery.Close;
SQLQuery.Params.ParamByName('SomeField').AsString:=SomeValue;
SQLQuery.Params.ParamByName('AnotherField').AsString:=AnotherValue;
... (setting more params, the same as the fields in the insert)
SQLQuery.Open;
NewID:=SQLQuery.FieldByName('AutoIncrementedPrimaryKey').AsInteger;

It seems to work but it's IMHO not very nice.
Ideally I'd like to have TSQLQuery do it for me and offer me some property like 
SQLQuery.LastInsertID or something along those lines.
Is there any way to get the new PK value without manually querying for the 
inserted record?

BTW the wiki (http://wiki.freepascal.org/Working_With_TSQLQuery) mentions that 
you should send 0 for the ID and add an appropriate 'ON DUPLICATE KEY' phrase 
to your SQL. I did not do this. I just omitted the ID in my SQLQuery.InsertSQL 
and AFAICT it works flawlessly.

R.

--
_______________________________________________
Lazarus mailing list
Lazarus@lists.lazarus.freepascal.org
http://lists.lazarus.freepascal.org/mailman/listinfo/lazarus

Reply via email to