【问题标题】:Anorm with SQL expressions as parameter values以 SQL 表达式作为参数值的异常
【发布时间】:2020-11-18 13:42:30
【问题描述】:

我正在尝试在 Scala 中使用 Anorm 创建此 SQL 语句。我正在使用 Postgres 数据库。

insert into my_table (coords) values (ST_GeomFromText('POINT(26.9484 24.03937)',4326)

我试过这段代码:

val lat = 26.9484
val long = 24.03937
val coords = s"ST_GeomFromText('POINT($lat $long)',4326)"
SQL"insert into my_table (coords) values (${coords})".executeInsert()

但我收到此错误:

[PSQLException: ERROR: subfield "coords" is of type geometry but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.

【问题讨论】:

    标签: scala anorm


    【解决方案1】:

    这是我的解决方案:

    val lat = Some(26.9484)
    val long = Some(24.03937)
    SQL"insert into my_table (coords) values (ST_MakePoint(${lat}, ${long}))".executeInsert()
    

    好处是,如果 lat 或 long 为 None (null),则表中的 coords 字段设置为 NULL。

    【讨论】:

    • 使用Some(..)是没用的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    相关资源
    最近更新 更多