【问题标题】:Play Anorm insert a scala List into a postgres text array column播放 Anorm 将 scala 列表插入到 postgres 文本数组列中
【发布时间】:2015-12-23 21:56:11
【问题描述】:

我正在尝试将 List[String] 插入到 text[] 类型的 postgresql 列中。我相信当您尝试插入任何列表时,Anorm 会将列表的每个成员插入其自己的列中。我很确定是这种情况,因为我得到了异常:

org.postgresql.util.PSQLException: ERROR: INSERT has more expressions than target columns

我想要做的是将整个列表作为文本 [] 插入。我当前的代码:

def insertList(listName: String, subLists: List[String]): Long = {
DB.withConnection{implicit c =>
SQL(
  """
    INSERT INTO mailinglists(name, sublists) VALUES({listName}, {subLists})
  """)
  .on('listName -> listName, 'subLists -> subLists)
  .executeInsert(scalar[Long] single)
}
}

我试图走这条路:

ConnectionPool.borrow().createArrayOf("text", subLists.toArray)

但我得到了错误:

type mismatch;
found   : (Symbol, java.sql.Array)
required: anorm.NamedParameter

【问题讨论】:

    标签: scala playframework-2.4 anorm


    【解决方案1】:

    最终解决此问题的代码是:

    def insertList(listName: String, subLists: List[String]): Long = {
    DB.withConnection{implicit c =>
      SQL"INSERT INTO mailinglists(name, sublists) VALUES($listName, ARRAY[$subLists])"
      .executeInsert(scalar[Long] single)
    }
    }
    

    与原帖不同的是使用了 Anorm 字符串插值 SQL"..." 并在多值参数周围添加了 ARRAY[...]。我不确定为什么这会起作用,因为 postgres 异常非常神秘。

    【讨论】:

      【解决方案2】:

      作为参数传递给 Anorm 的值不应是原始 JDBC 值。你不应该传递java.sql.* 值;你可以看看parameter mappings

      然后您将参数名称传递为Symbol,它在 Anorm 2.3 中已被弃用,并且自 2.4 起不再支持。名称必须以String 传递。

      SQL 数组可以作为Array[T] 传递,支持T 作为参数类型。

      您还可以查看有关 multi-value parameters 的文档。

      【讨论】:

      • 所以我使用 .toArray 转换了列表,它已解决,但现在我得到“org.postgresql.util.PSQLException: Unable to find server array type for provided name VARCHAR”。它被插入的列是一个文本[]。
      • 当异常应该传递“varchar”时,它是否传递了一些类型转换“VARCHAR”?
      • 这里你可以看到异常使用“VARCHAR”作为“sqlType”和jdbcType github.com/playframework/anorm/blob/…
      • PostgreSQL 无关紧要。你的问题在别处。你可以试试多值SQL"INSERT INTO mailinglists(name, sublists) VALUES($listName, ARRAY[$subLists])"
      • 因此,通过 VARCHAR 异常的关键是将我的 SQL 切换为字符串插值。但是,现在我遇到了另一个神秘的 psql 异常。如果我使用您建议的代码运行它,INSERT INTO mailinglists(name, sublists) VALUES($listName, ARRAY[$array]) 我会得到 org.postgresql.util.PSQLException: ERROR: syntax error at or near ";"位置:86` 如果我在没有 ARRAY[...] 的情况下执行它,我会得到:`org.postgresql.util.PSQLException: ERROR: syntax error at or near "[" Position: 62` SQL 语句在异常
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      相关资源
      最近更新 更多