【问题标题】:Anorm replacement of params gives error on usage of aggregate functions参数的异常替换会在使用聚合函数时出错
【发布时间】:2021-09-27 21:30:12
【问题描述】:

表结构-

create table test
(month integer,
year integer,
thresholds decimal(18,2)
);

用于模拟的静态插入 -

insert into test(month,year,threshold) values(4,2021,100),(5,2021,98),(6,2021,99);

如果我使用anorm 查询postgres 数据库,它适用于常规查询。但是在添加像 max 这样的聚合函数时,RowParser 无法找到别名列。

val queryString =
  """select max(month) as monthyear from test
     | where (month || '-' || year)
     | = {inQuery}""".stripMargin

    val inQuery1 = "'5-2021'"

下面的on 方法会导致问题 -

val latestInBenchmark = SQL(queryString).on("inQuery" -> inQuery1) // removing the on resolves the problem

logger.info("query for latest period ---> " + latestInBenchmark)

val latestYearMonthInInterval = database.withConnection(implicit conn => {
          latestInBenchmark.as(SqlParser.int("monthyear").*)
        })

删除on 可以解决问题,SqlParser.int(column-name) 可以按预期工作。 这也不会影响使用 count 聚合函数的查询。

遇到错误:

(Validated intervals with sorting -> ,Failure(anorm.AnormException: 'monthyear' not found, available columns: monthyear, monthyear))
[error] c.b.ThresholdController - 'monthyear' not found, available columns: monthyear, monthyear

【问题讨论】:

  • 你永远不应该使用带参数的字符串插值,请先阅读文档
  • 也许 OP 在此期间更改了帖子,但这里没有字符串插值。
  • 它在没有字符串插值的情况下发生。这是一个复制粘贴错误,因为我使用字符串插值来解决异常参数错误

标签: scala anorm sql-parser


【解决方案1】:

您遇到的错误有点误导,但这意味着查询要么返回具有空值的行,要么没有行。

在您的情况下,我认为问题在于 WHERE 子句:您在值周围加上了单引号,但在使用 .on(...) 或 Anorm 插值时,Anorm 会自行完成。

因此,替换:

val inQuery1 = "'5-2021'"

作者:

val inQuery1 = "5-2021"

【讨论】:

  • sql 工作并返回一行。尝试删除单引号,但给了我同样的错误。
  • @ForeverLearner,然后我会尝试调试响应解析中发生的事情。您应该能够访问查询返回的原始数据,并且可能了解错误。
  • 如果你看过documentation,里面有很多传参的例子,明确表示不能自己引用。与任何体面类型的库一样,如果您想传递可空的 T,Anorm 期望 Option[T]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多