gpt4 book ai didi

scala - Play Framework 2.0 使用 Anorm 在查询中表示集合的正确方法

转载 作者:行者123 更新时间:2023-12-02 22:07:39 26 4
gpt4 key购买 nike

我正在尝试使用 Anorm 返回结果列表,该查询使用返回一组 ID 的匹配行的查询。例如。

select *
from example
where id in (1,2,3,4,5)

如果我尝试

SQL(
"""
select *
from example
where id in ({ids})
"""
).on('ids -> ids).as(int("id") ~ str("name") *)

其中 ids 是字符串“1,2,3,4,5”,它只会返回第一行。注入(inject) ID 集的正确方法是什么?

最佳答案

据我所知,没有简单的方法可以做到这一点。

我是这样解决的:

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") *
)
}
}

注意
这里的关键部分是 SQL 语句中的字符串格式。如果您不能完全控制您的输入参数,它很容易受到 SQL 注入(inject)攻击。

关于scala - Play Framework 2.0 使用 Anorm 在查询中表示集合的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15864564/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com