我使用 postgresql 9.5 和 jdbc 驱动程序 9.4.1208.jre7 和 scalikejdbc 包装器
我的 table 是:
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
}
但它给了我异常(exception):org.postgresql.util.PSQLException:未知类型 ARRAY
可能是我错过了一些东西,但我找不到关于 PGObject 类的好文档。我认为 PGObject 类是专门为像我这样的目的而设计的,但它的行为并不符合预期
POSTGRES 有多种类型,不仅有数组,还有日期、日期时间、日期范围、时间戳范围等。我认为其对应的类型应该有类型名称。
最佳答案
我了解了如何使用 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
}
关于postgresql jdbc、pgobject可用类型、数组类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35669973/