在play框架SQL anorm中插入两个值列表

时间:2015-08-12 13:43:50

标签: mysql scala playframework playframework-2.3 anorm

目前我正在开发Playframework。我需要使用Anorm将两个List值插入数据库。一个是names: List[String],另一个是numbers: List[Int],它们都具有相同的大小。

我需要在names的同一numbers List中插入Row的第一个位置和Database Table的第一个位置,就像明智地需要在{{1}中插入所有值一样}}

我试过了:

Lists

它给出了以下错误 for (no<- 0 to (names.size-1)) { SQL( """ insert into table(NAME,NUMBER) values( names[{no}],numbers[{no}] ) """).on( 'no-> no ).executeUpdate() }

我也试过

[MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[0],numbers[0]

但是它像java中一样充当 for (name<- names;number<- numbers) { SQL( """ insert into table(NAME,NUMBER) values( {name},{number} ) """).on( 'name-> name, 'number-> number ).executeUpdate() }

two for loops

2 个答案:

答案 0 :(得分:2)

names[{no}]的SQL语句无法以任何方式工作:数据库没有Scala值names

您可以使用.zipped

scala> (List("A", "B"), List(1.2F, 34.5F)).zipped.foreach { (str, f) => println(s"zipped: $str -> $f") }
zipped: A -> 1.2
zipped: B -> 34.5

然后Anorm执行如下。

(names, numbers).zipped.foreach { (name, num) =>
  SQL"insert into table(NAME,NUMBER) values($name, $num)".executeUpdate()
}

答案 1 :(得分:0)

您应该首先使用zip组合这两个列表,这样您就有了一个列表,其中每个列表元素都是名称和数字的元组:

val names = List("bob", "steve", "frank")

val numbers = List(1,2,3)

val name_and_numbers = names zip numbers

name_and_numbers.foreach{ tuple =>
  println(s"name: ${tuple._1} number: ${tuple._2}")
}
相关问题