目前我正在开发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
答案 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}")
}