0

我正在使用带有 scala 的游戏框架,并且我正在将值存储到数据库中,但是我收到错误如何在数据库中插入值

我在做什么:

  1. 我从表单中获取值,然后对数据执行一些操作,然后将值存储在数据库中。

我经历了解决方案,但他们提供的解决方案在我的应用程序中不起作用

应用进化文件:

# --- !Ups
create table keyword (
  id                        bigint  not null AUTO_INCREMENT primary key,
  word                       varchar(255) not null ,
  blog                       varchar(255) not null ,
  cat                       varchar(255) not null ,
  score                       BIGINT not null ,
  summaryId                       varchar(255) not null,
  dates                             datetime 

);

# --- !Downs

drop table keyword;

模型/keyword.scala文件

case class Keyword(id: Pk[Long] = NotAssigned,word: String,blog: String,cat: String,score: Long, summaryId: String)

object Keyword {


  val keyw = {
     get[Pk[Long]]("keyword.id") ~
     get[String]("keyword.word")~
    get[String]("keyword.blog")~
    get[String]("keyword.cat")~
    get[Long]("keyword.score") ~ 
    get[String]("keyword.summaryId")map {
    case id~word~blog~cat~score~summaryId => Keyword(id,word,blog,cat,score, summaryId)
  }
}

  def all(): List[Keyword] = DB.withConnection { implicit c =>
  SQL("select * from keyword").as(Keyword.keyw *)
}

def ad(word: String, count: Long, summaryId: String, blog: String, cat: String)={DB.withConnection{implicit c=> 
  val id=SQL("select id from keyword").apply.head

  SQL("insert into keyword values({id},{word},{blog}, {cat}, {score},{summaryId},{dates})").on('id->Id(id),
      'word-> word,'blog->blog,
      'cat -> cat,
      'score-> count,
      'summaryId -> summaryId,
      'dates-> new DateTime().toDate()).executeUpdate}}

控制器文件:

我正在调用广告方法插入数据库

Keyword.ad(k.word, k.count, link, blog, category)

但我不知道如何将主值 id 插入作为主键的数据库中。

我设置idprimary keyauto- increment

但是当我调用这个方法时, 我没有得到如何赋予 id 价值

任何人都可以给我一些想法来解决这个问题吗?

4

1 回答 1

2

我认为您不应该直接从您的代码中插入 PK Id 值,- db 会为您执行此操作,并将为您提供新的自动增量值。

只需从查询中删除与 id 相关的语句:

SQL("insert into keyword values({word},{blog}, {cat}, {score},{summaryId},{dates})").on(
      'word-> word,'blog->blog,
      'cat -> cat,
      'score-> count,
      'summaryId -> summaryId,
      'dates-> new DateTime().toDate()).executeInsert()}}

希望这会有所帮助。

UPD:另外,请使用 executeInsert 方法。在这里您可以找到如何从数据库中获取您的 ID: How to Retrieve the Primary Key When Saving a New Object in Anorm

于 2013-11-04T09:31:20.963 回答