使用anorm将多个值插入表中 [英] Inserting multiple values into table with anorm
本文介绍了使用anorm将多个值插入表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从Anorm中的SQL查询向表中插入多个值.在以下代码段中,是否可以将一系列用户名绑定为值而不是一个用户名?
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()
作为替代方案,我可以从输入中创建一个串联的字符串,但这很容易进行SQL注入,而且不太干净.
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.
推荐答案
使用Anorm一次插入多个值的一种可能方法:
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()
这篇关于使用anorm将多个值插入表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文