【问题标题】:Inserting multiple values and fields into table with anorm使用异常将多个值和字段插入表中
【发布时间】:2014-10-16 14:47:46
【问题描述】:

我发现这个答案可以解决一个领域 -> Inserting multiple values into table with anorm

   var fields: List[String] = Nil
var values: List[(String,ParameterValue[_])] = Nil

for ((username,i) <- usernames.zipWithIndex) {
  fields ::= "({username%s})".format(i)
  values ::= ("username" + i, username)
}

SQL("INSERT INTO users (username) VALUES %s".format(fields.mkString(",")))
  .on(values: _*)
  .executeUpdate()

如何传递更多字段,例如用户名、地址、电话号码等?

我试过了……

 def create(names: List[(String,ParameterValue[_])] ,addresses :List[(String,ParameterValue[_])]){

   var fields: List[String] = Nil;

   for((a,i) <- names.zipWithIndex){
      fields ::= "({name%s},{address%s})".format(i)
   }
           DB.withConnection { implicit c =>

           SQL("insert into table (name,address) values  %s".format(fields.mkString(",")))
          .on(names: _*, addresses: _*)
          .executeUpdate()
           }
 }

我收到以下错误: "此处不允许使用 "_ *" 注释"

如果我可以对所有参数使用一个列表,那就更好了。

【问题讨论】:

    标签: mysql scala playframework anorm


    【解决方案1】:

    您基本上想要执行批量插入。这是从文档中摘录的改编:

    import anorm.BatchSql
    
    val batch = BatchSql(
      "INSERT INTO table (name, address) VALUES({username}, {address})", 
      Seq(names, addresses)
    )
    
    val res: Array[Int] = batch.execute() // array of update count
    

    【讨论】:

    • 代码中的名称和地址是我的列表作为参数接收的吗?是否可以使用单个列表,以这种方式回答?
    • 我收到以下错误:“NoSuchElementException: key not found : address”
    猜你喜欢
    • 2013-01-18
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    相关资源
    最近更新 更多