【问题标题】:How to insert a new row into a database and obtain the primary key as a result如何将新行插入数据库并获取主键作为结果
【发布时间】:2012-08-31 11:48:35
【问题描述】:

我正在使用带有 Anorm 的 Play2。有没有办法执行 INSERT 语句并获取自动生成的主键作为结果?

【问题讨论】:

  • 执行此操作的原始 PostgreSQL 方法是通过 INSERT ... RETURNING 语句。通过 JDBC,您应该能够使用 JDBC 的支持来获取生成的密钥。玩...?

标签: postgresql playframework playframework-2.0 postgresql-9.1 anorm


【解决方案1】:

使用RETURNING clause

INSERT INTO tbl(foo)
VALUES ('bar')
RETURNING foo_id;

Anorm 可能看起来像这样(我不是 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”)

【讨论】:

  • 是的,我结束了这样的事情: SQL("INSERT INTO tbl(foo) VALUES ('bar') RETURNING foo_id").as(scalar[Long].single)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
  • 2021-06-20
  • 2019-03-05
相关资源
最近更新 更多