简体   繁体   English

使用Clojure访问数据库

[英]Accessing a database with Clojure

Here is a simple question concerning Clojure and accessing information from a database. 这是一个有关Clojure和从数据库访问信息的简单问题。

The following code, inside a function of mine is working: 我的函数内部的以下代码正在运行:

(defn insertNewValue []
(let [newRank
        (reduce + 1
          (map :max
            (db/query (env :database-url) ["select max(rank) from My_Table"])))
      .........

But using reduce when there is only one record resulting from the DB query does not seem very appropriate to me. 但是,在数据库查询仅产生一条记录时使用reduce似乎对我来说并不适合。 So here is what I tried as a replacement: 所以这是我尝试的替代品:

(defn insertNewValue []
(let [dbRecord (db/query (env :database-url) ["select max(rank) from My_Table"])
      newRank (+ 1 (:max dbRecord))
      .........

which seems much cleaner, but it does not work! 看起来更干净了,但是不起作用!

Can anyone tell me what I am doing wrong? 谁能告诉我我在做什么错?

It seems that dbRecord would return a list (thats why you could map over it), however, in your second attempt you are treating it as a map directly. 似乎dbRecord将返回一个列表(这就是为什么可以在其上进行map的原因),但是,在第二次尝试中,您将其直接视为映射。 Since it is guaranteed that you only have a single record (you are querying for the max value), perhaps you need to do 由于可以确保只有一条记录(您正在查询最大值),因此也许您需要

(inc (:max (first dbRecord)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM