Common CRUD design issue - getting a newly added entity's ID
Is there any built-in database function (any 开发者_如何学Godb) that does something like this? Ie. ask the db to create a record and then return the ID that was automatically assigned to it.
Try this
INSERT INTO table_name
(id, value)
VALUES
id_value, value
RETURNING id
INTO item_id;
For MySQL:
INSERT INTO table_name
(id, value) /** assuming ID is a PRIMARY KEY with AUTOINCREMENT **/
VALUES
(null, value);
SELECT LAST_INSERT_ID();
The LAST_INSERT_ID() function will send the last generated autoincrement number, per connection.
精彩评论