【问题标题】:postgresql jdbc, pgobject available types, array typepostgresql jdbc,pgobject 可用类型,数组类型
【发布时间】:2016-02-27 12:47:45
【问题描述】:

我使用带有 jdbc 驱动程序 9.4.1208.jre7 和 scalikejdbc 包装器的 postgresql 9.5

我的桌子是:

CREATE TABLE refs
(
  name character varying NOT NULL,
  custom json,
  prices integer[]
)

我可以使用 org.postgresql.util.PGobject 插入 json 值:

val res = new PGobject()
res.setType("json")
res.setValue("{'name': 'test'}")
res

我还想插入数组。我怎样才能做到这一点?我认为这会起作用:

  def toArrStr(a: Iterable[String]): PGobject = {
    val res = new PGobject()
    res.setType("ARRAY")
    res.setValue(s"{${a.map(i => '"' + i + '"').mkString(",")}}")
    res
  }

但它给了我一个例外:org.postgresql.util.PSQLException: Unknown type ARRAY

可能是我错过了 smth 但我找不到关于 PGObject 类的好文档。我认为 PGObject 类是为像我这样的目的而设计的,但它的行为并不像预期的那样

POSTGRES 有很多类型,不仅是数组,还有日期、日期时间、日期范围、时间戳范围等。我认为应该有对应类型的类型名称。

【问题讨论】:

  • 一些注意事项:您可能应该使用 Java 中的接口类,例如 java.sql.Array,而不是内部 PostgreSQL 实现。第二:PosgreSQL JDBC 的内部javadochere。第三:PostgreSQL对JSON-data typesfunctions to manipulate them有很好的原生支持。
  • marcospereira,您提供的答案不使用 PGobject
  • zloster,首先:我想使用内部 postgrSQL 实现,因为编写 '{"my", "str", "array"}' 然后使用 java 类型,尝试从scala类型到java只是为了更新列。第二:感谢链接。第三:我已经知道 postgres 有原生 json 支持,那么你有什么建议?忘记数组原生类型并在 json/jsonb 字段中保留任何数据?第四:我不是唯一一个用PGObject的,看stackoverflow.com/questions/19599346/…

标签: postgresql scala jdbc scalikejdbc


【解决方案1】:

我了解如何使用 PGObject 保存字符列表[]:

  def toArrStr(a: Iterable[String]): PGobject = {
    val res = new PGobject()
    res.setType("varchar[]")
    res.setValue(s"{${a.map(i => '"' + i + '"').mkString(",")}}")
    res
  }

保存数字数组: 其中大小为 2,4,8 (smallint, int, bigint)

  def toArrNum(a: Iterable[AnyVal], size: Int): PGobject = {
    val res = new PGobject()
    res.setType(s"int$size[]")
    res.setValue(s"{${a.mkString(",")}}")
    res
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    相关资源
    最近更新 更多