【问题标题】:Inserting data into postgresql json columns using clojure.java.jdbc使用 clojure.java.jdbc 将数据插入到 postgresql json 列中
【发布时间】:2016-05-06 09:57:15
【问题描述】:

我正在尝试使用clojure.java.jdbc/insert! 插入到 postgresql 数据库中的 json 列中。我不确定插入json时应该使用哪种数据格式。

表定义:

CREATE TABLE errors (
    id character varying(24) NOT NULL PRIMARY KEY,
    body json NOT NULL
);

尝试使用地图格式的文字数据:

=> (insert! db :errors {:id "a" :body {:message "A error"}}
                       {:id "b" :body {:message "B error"}})
PSQLException No hstore extension installed.  org.postgresql.jdbc2.AbstractJdbc2Statement.setMap (AbstractJdbc2Statement.java:1709)

或者作为 json 编码的字符串:

=> (insert! db :errors {:id "a" :body "{\"message\":\"A error\"}"}
                       {:id "b" :body "{\"message\":\"B error\"}"})
PSQLException ERROR: column "body" is of type json but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.
  Position: 46  org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse (QueryExecutorImpl.java:2198)

似乎没有明显的方法可以做到这一点。特别重要的是,我需要能够在单个查询中插入多条记录,而不是一条一条地插入,insert! 为我提供了便利。

使用 clojure.java.jdbc 将多条记录插入到具有 json 列的 postgres 表中的简单方法是什么?

【问题讨论】:

    标签: json postgresql jdbc clojure


    【解决方案1】:

    由于 clojure.java.jdbc 公开了一些协议,包括 clojure.java.jdbc/ISQLValue,您可以对其进行扩展以允许将 json 作为普通的 clojure 映射提供。 Travis Vachon 提供了a thorough explanation of this process 和一个实现它的代码 sn-p。

    我还发现了一个库,clj-postgresql,它实现了许多额外的 postgres 功能,包括 json 和 jsonb 数据类型。您可以简单地要求 clj-postgresql.types 并且将导入 json 支持。

    【讨论】:

    • “彻底解释此过程”的链接已失效!你有其他来源吗?
    • @rdgd 将其替换为 Internet 存档链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 2017-08-17
    • 2019-11-20
    • 2018-12-10
    • 2016-09-01
    相关资源
    最近更新 更多