Inserting multiple values into table with anorm

岁酱吖の 提交于 2020-01-02 05:54:07

问题


I want to insert multiple values into a table from a SQL query in Anorm. In the following snippet, is there a way to bind a list of usernames as values instead of just one username?

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

As an alternative, I can create a concatenated string from my inputs, but that's prone to SQL injection and isn't quite as clean.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/14675862/inserting-multiple-values-into-table-with-anorm

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