Inserting multiple values into table with anorm

感情迁移 提交于 2019-12-05 14:46:25

A possible way to insert multiple values at once, using 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()

You're wanting to repeat the insert command for all of the values?

How about wrapping it in a foreach:

usernames.foreach(username =>
  SQL("insert into users (username) " +
    "values ({username})").on(
    'username -> username,
  ).executeUpdate())

Or something of that sort.

Anorm is a relatively simple library--check out the code here: https://github.com/playframework/Play20/tree/master/framework/src/anorm/src/main/scala/anorm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!