How to insert a new row into a database and obtain the primary key as a result
-
29-06-2021 - |
Question
I'm using Play2 with Anorm. Is there a way to execute an INSERT statement and obtain the automatically generated primary key as a result?
Solution
Use the RETURNING
clause:
INSERT INTO tbl(foo)
VALUES ('bar')
RETURNING foo_id;
With Anorm it could look like this (I am not an expert with Anorm):
import play.db.anorm._
val firstRow = SQL("INSERT INTO tbl(foo)
VALUES ('bar') RETURNING foo_id").apply().head
val foo_id = firstRow[int](“foo_id”)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow