Page 1 of 1

Output parameters in INSERT query

Posted: Tue 09 Jul 2013 09:57
by dbxDmitry
Delphi XE4. dbExpress for Sqlite3.

Hello everyone. I'm trying to obtain autoincremented primary key value of inserted row. Like this:
SQLQuery.CommandText := 'INSERT INTO tbl1 (id, name) VALUES (:id, :name)';
SQLQuery.ParamByName('id').ParamType := ptInputOutput;
SQLQuery.ExecSql();

Inserting works fine, but when I'm trying to get back my id parameter, it is always 0:
SQLQuery.ParamByName('id').Value <--- 0

How can I get autogenerated key for inserted row atomically?
Thank you!

Re: Output parameters in INSERT query

Posted: Wed 10 Jul 2013 13:15
by AlexP
Hello,

To retrieve the value of the auto-incremental field, you should use the SQLite last_insert_rowid function

Code: Select all

SELECT last_insert_rowid()

Re: Output parameters in INSERT query

Posted: Wed 10 Jul 2013 15:50
by dbxDmitry
AlexP wrote:Hello,

To retrieve the value of the auto-incremental field, you should use the SQLite last_insert_rowid function

Code: Select all

SELECT last_insert_rowid()
Thank you. But is this will be an atomic operation? I mean what if someone else inserted something in this table?

Re: Output parameters in INSERT query

Posted: Thu 11 Jul 2013 10:05
by dbxDmitry
Found answer on last question myself here http://www.sqlite.org/c3ref/last_insert_rowid.html

Thank you.

Re: Output parameters in INSERT query

Posted: Fri 12 Jul 2013 07:16
by AlexP
Hello,

Glad to see that you solved the problem. If you have any other questions, feel free to contact us