[英]How to add a record to an existing map?
I have a map obtained from running a sql query. 我有从运行sql查询获得的地图。
(defn print-info
[rs]
(doseq [req rs]
(let [rs1 req]
(println "rs1" rs1))))
(defn display-info
[uname]
(sql/with-connection
db
(sql/with-query-results rs
["Select * from user"]
(print-info rs))))
Now i have copied the result set into another map. 现在,我已将结果集复制到另一张地图中。 Is there any way to add another record to this existing map and return this new map to another function ? 有什么方法可以将另一个记录添加到此现有映射并将此新映射返回给另一个函数?
If you use the non-deprecated query
syntax which was explained in your other question , you can use the :row-fn
to manipulate each record in a resultset. 如果您使用另一个问题中未说明的query
语法,则可以使用:row-fn
操作结果集中的每个记录。 A default row is a map, so if you use only functions that return a map (like in this case select-keys
), you can just use assoc
to add a new key-value pair to the map. 默认行是地图,因此,如果仅使用返回地图的函数(如本例中的select-keys
),则可以使用assoc
向地图添加新的键值对。
(query db ["select * from user"]
:row-fn #(assoc (select-keys % [:name]) :type :user))
Generally speaking when I want to make a fix to a record I'll use merge , which merges any number of maps in a left-to-right direction. 一般来说,当我想对记录进行修复时,我将使用merge ,它会沿左右方向合并任意数量的地图。 Thus: 从而:
user=> (merge {:foo 1 :bar 2 :ban 3} {:bar 20} {:ban 300})
{:foo 1, :bar 20, :ban 300}
Although the assoc approach mentioned above also works, I find merge generally more useful and more flexible. 尽管上面提到的assoc方法也可行,但我发现合并通常更有用和更灵活。
This applies to anything represented as a map, of course, not just records! 当然,这适用于以地图表示的任何内容,而不仅仅是记录!
As an aside I'd strongly recommend using [Korma| 另外,我强烈建议您使用[Korma | http://sqlkorma.com/] for your database queries. http://sqlkorma.com/]进行数据库查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.