Search code examples
mysqlscalaplayframeworkplayframework-2.3anorm

Insert Two List of values in play framework SQL anorm


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(){}
}

Solution

  • 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.5
    

    Then the Anorm execution would be as following.

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