Mat*_*ing 2 scala anorm playframework-2.0
我试图使用Anorm返回一个结果列表,使用一个返回一组id的匹配行的查询.例如.
select *
from example
where id in (1,2,3,4,5)
Run Code Online (Sandbox Code Playgroud)
如果我试试
SQL(
"""
select *
from example
where id in ({ids})
"""
).on('ids -> ids).as(int("id") ~ str("name") *)
Run Code Online (Sandbox Code Playgroud)
其中id是字符串"1,2,3,4,5",它只返回第一行.注入一组id的正确方法是什么?
没有简单的方法来做AFAIK.
这就是我解决它的方式:
def findSomething(ids: String) = {
// Split up the comma separated values
val sids = ids split ","
// Create a list of keys (id0, id1, id2, ...)
val keys = for ( i <- 0 until sids.size ) yield ("id" + i)
// Create a seq of parameterized values
val values = sids map (toParameterValue(_))
// Now zip together the keys and values into list of tuples
val params = keys zip values
DB.withConnection { implicit connection =>
SQL(
"""
select *
from example
where id in ({%s})
""".format(keys.mkString("},{"))
).on(
params: _*
).as(
int("id") ~ str("name") *
)
}
}
Run Code Online (Sandbox Code Playgroud)
NB
这里的关键部分是SQL语句中的字符串格式.如果您没有完全控制输入参数,那么它很容易被SQL注入.