0

我将 clojure 与 jdbc、compojure、cheshire、postgresql、c3p0、tryin make REST 一起使用。当我将此代码用作处理程序时

  (defn get-document [id]
      (sql/query (db-connection)
                 ["select * from document where id = cast(? as integer)" id]
                 {:row-fn
                  (fn [first]
                                   (if (empty? first )
                                     (response "empty")
                                     (response first)
                                     ))}))

如果 reslutset 不为空,我会根据需要进行响应,但如果它为空,我会得到空括号 []。

这也是我的项目依赖项

  :dependencies [[org.clojure/clojure "1.8.0"]
                 [compojure "1.5.1"]
                 [ring/ring-json "0.4.0"]
                 [c3p0/c3p0 "0.9.1.2"]
                 [ring/ring-defaults "0.2.1"]
                 [org.clojure/java.jdbc "0.7.3"]
                 [org.postgresql/postgresql "42.1.4"]
                 [cheshire "5.8.0"]]
4

1 回答 1

1

:row-fn函数针对结果集中的每一行执行。当您的结果集为空时,不会调用 row-fn。

您可能需要使用 的结果sql/query来处理查询的响应。当没有结果时,返回一个空向量(这是[])。您可以通过调用来检查结果是否为空empty?。像这样的东西:

(defn get-document [id]
  (let [query ["select * from document where id = cast(? as integer)" id]
        rows  (sql/query (db-connection) query)]
      (if (empty? rows)
        (response "empty")
        (response (first rows)))))
于 2017-10-12T09:52:35.580 回答