目前我正在开发Playframework。 我需要使用Anorm将两个List值插入数据库。 一个是names: List[String] ,另一个是numbers: List[Int] ,它们都具有相同的大小。
我需要在Database Table中的同一Row中插入names第一个位置和numbers List第一个位置,就像明智地需要在两个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] [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]
我也尝试过
for (name<- names;number<- numbers) { SQL( """ insert into table(NAME,NUMBER) values( {name},{number} ) """).on( 'name-> name, 'number-> number ).executeUpdate() }但它像java中的two for loops一样充当了two for loops 。
for(){ for(){} }Currently I am working on Playframework. I need to insert two List values into the database by using Anorm. One is names: List[String] and another one is numbers: List[Int], and they both have the same size.
I need to insert first position of names and first position of numbers List in same Row in Database Table like wise need to insert all values in the both Lists.
I tried :
for (no<- 0 to (names.size-1)) { SQL( """ insert into table(NAME,NUMBER) values( names[{no}],numbers[{no}] ) """).on( 'no-> no ).executeUpdate() }It gives me the below error [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]
and I also tried with
for (name<- names;number<- numbers) { SQL( """ insert into table(NAME,NUMBER) values( {name},{number} ) """).on( 'name-> name, 'number-> number ).executeUpdate() }but it was act as two for loops like in java.
for(){ for(){} }最满意答案
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() }The SQL statement with names[{no}] cannot work in any way: the database doesn't have the Scala value names.
You can use .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.5Then the Anorm execution would be as following.
(names, numbers).zipped.foreach { (name, num) => SQL"insert into table(NAME,NUMBER) values($name, $num)".executeUpdate() }更多推荐
发布评论