我正在努力将记录插入postgresql:
val res = DB.withConnection {
implicit con =>
SQL(
"""INSERT INTO
my_table(id, user_id, file_name, added_at)
VALUES(DEFAULT, {userId}, {fileName}, {currentTime})
RETURNING id
""")
.on("userId" -> 1, "fileName" -> "fileName1", "currentTime" -> new java.sql.Timestamp(DateTime.now.getMillis))
.executeInsert()
}
Ok(toJson(JsObject(Seq("res" -> JsString(res.toString)))))
它确实插入了一个值(我可以通过pdAdmin看到),但最终会返回错误ERROR: syntax error at or near "RETURNING"
。
如果我删除RETURNING id
,则错误将变为TypeDoesNotMatch(Cannot convert requestBody4050249427671619471asTemporaryFile :class java.lang.String to Long for column ColumnName(my_table.file_name,Some(file_name)))]]
当我切断id
和DEFAULT
时,错误仍然相同。
my_table
定义的是
CREATE TABLE my_table
(
file_name character(255),
user_id integer,
added_at timestamp without time zone,
id serial NOT NULL,
CONSTRAINT my_table_pk PRIMARY KEY (id),
CONSTRAINT scan_fk FOREIGN .....
)
为什么?它与file_name
有什么关系?
答案 0 :(得分:1)
鉴于此表:
CREATE TABLE my_table
(
file_name character(255),
user_id integer,
added_at timestamp without time zone,
id serial NOT NULL,
CONSTRAINT my_table_pk PRIMARY KEY (id)
);
您可以插入记录并检索其ID,如下所示:
package dao
import anorm._
import anorm.SqlParser._
import play.api.db.DB
import play.api.Logger
import play.api.Play.current
object MyDAO {
def insert(fileName: String, userId: Int): Int = {
val sql = SQL(
"""
insert into my_table(file_name, user_id, added_at)
values ({fileName}, {userId}, CURRENT_TIMESTAMP)
returning id
""")
.on(
"fileName" -> fileName,
"userId" -> userId)
DB.withConnection { implicit c =>
val id = sql.as(scalar[Int].single)
Logger.info(s"Inserted '$fileName' with id '$id'.")
id
}
}
}
并按照以下方式进行测试:
import org.junit.runner._
import org.specs2.mutable._
import org.specs2.runner._
import play.api.test._
import play.api.test.Helpers._
import dao.MyDAO
@RunWith(classOf[JUnitRunner])
class MyDAOSpec extends Specification {
"MyDAO" should {
"insert a record and return its id" in new WithApplication {
val id = MyDAO.insert("file1", 101)
id must be_>=(0)
}
}
}
有关如何从结果集中检索数据的更多示例,请参阅Anorm, simple SQL data access。