mysql - 使用 anorm 将多个值和字段插入表中

标签 mysql scala playframework anorm

我发现这个答案可以解决一个字段 -> 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()
           }
 }

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

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

最佳答案

您基本上想要执行批量插入。以下是对文档的改编:

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

关于mysql - 使用 anorm 将多个值和字段插入表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26407357/

相关文章:

java - 将选定的 Jtree 节点设置为 JTable

MySQL表链接1 :n

mysql - 如何在 mysql 查询中使用交叉表或数据透视表动态获取月份名称?

generics - 关于 Scala 泛型的简单问题

java - 通过 Java 创建 Kafka 主题时出错

Play 2.1.1中Json写入

java - 如何为 swagger 注释 Play 2 webapp 模型?

mysql - 如何将表的每一行中的特定列设置为唯一值?

scala - 在 Scala 中定义子类型的排序

playframework - IntelliJ IDEA 可以自动导入 Play 依赖项吗?