我正在使用clojure与jdbc,compojure,cheshire,postgresql,c3p0,试着制作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"]]
答案 0 :(得分:1)
The :row-fn
function is executed for each row in the result set. When your result set is empty, row-fn is not called.
You may need to use the result of sql/query
to handle the response of the query. When there is no result an empty vector is returned (this is []
). You can check if the result is empty by calling empty?
. Something like this:
(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)))))