我正在使用 Clojure、YeSQL 和 Postgres。
我有一个像这样的简单 postgres 表:
CREATE TABLE foo (
id SERIAL PRIMARY KEY,
num INT NOT NULL DEFAULT 1,
txt TEXT NOT NULL
);
我在文件中有一个查询,如下所示:
SELECT (id, num, txt) FROM foo WHERE id = :id
我预加载数据库:
INSERT INTO foo (num, txt) VALUES (5, 'potato');
当我通过 yesql 加载查询并在 repl 中运行它时,我得到了这个结果:
=> (yesql/defquery get-record "foo.sql")
nil
=> (def rec (get-record 1))
({:row #<PGobject (1,5,"potato")>})
我完全不知道如何使用 PGobject...我试着查看一些说明 (https://jdbc.postgresql.org/documentation/publicapi/org/postgresql/util/PGobject.html),但显然我不知道如何使用那里的任何东西。
我希望能得到类似 map 的东西,也许:
{:id 1
:num 5
:txt "potato"}
但我刚得到这个 PGobject 东西,我不知道如何从中获取数据。是否有某种可用的方法可以让我获得,例如 (:num rec)
之类的 num 或 txt(这是我期望我可以做的)。
即使我能弄清楚如何将 PGobject 转换为我认识的某种 clojure 数据类型,我也会很高兴。帮忙?
最佳答案
好的,我想通了。问题是我查询中的分组。我使用的查询:
SELECT (id, num, txt) FROM foo WHERE id = :id
将结果分组在括号中。这会导致 Postgres JDBC 驱动程序将结果作为分组集返回,这不是 JDBC 驱动程序能够很好理解的数据类型。
相反,我应该使用:
SELECT id, num, txt FROM foo WHERE id = :id
在这种情况下,而不是 ({:row #<PGobject (1,5,"potato")>})
(第一个查询的结果)我得到了更好的 ({:id 1, :num 5, :txt "potato"})
.
相关信息终于来自本站http://www.postgresql.org/docs/7.1/static/jdbc-ext.html ;特别是以下部分:
This allows client code to add a handler for one of PostgreSQL's more unique data types. Normally, a data type not known by the driver is returned by ResultSet.getObject() as a PGobject instance. This method allows you to write a class that extends PGobject, and tell the driver the type name, and class name to use. The down side to this, is that you must call this method each time a connection is made.
关于postgresql - 在 Clojure 中使用 PGobject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32665464/