Clojure 新手求教(sql/with-connection mysql-db
(sql/insert-records :fruit
{:name "Apple" :appearance "rosy" :cost 24}
{:name "Orange" :appearance "round" :cost 49}
{:name "Orange" :appearance "round" :cost 49}
.
.
.
))
1 回答
摇曳的蔷薇
TA贡献1793条经验 获得超6个赞
一般来说可以直接使用insert!函数,比如
(defn insert-rows-fruit "Insert complete rows" [db] (j/insert! db :fruit nil ; column names not supplied [1 "Apple" "red" 59 87] [2 "Banana" "yellow" 29 92.2] [3 "Peach" "fuzzy" 139 90.0] [4 "Orange" "juicy" 89 88.6]))
也可以这样使用:
(defn insert-records-fruit "Insert records, maps from keys specifying columns to values" [db] (j/insert! db :fruit {:name "Pomegranate" :appearance "fresh" :cost 585} {:name "Kiwifruit" :grade 93}))
有需要逐条插入的话可以使用doseq 比如
(doseq [to-insert [{:name "Apple" :appearance "rosy" :cost 24} {:name "Orange" :appearance "round" :cost 49} {:name "Orange" :appearance "round" :cost 49}]] (sql/insert-records :fruit to-insert))
你还可以使用zipmap函数, zipmap函数接受一组键和一组值,返回一个hash-map,相当于
(apply hash-map (apply concat (interleave [:k1 :k2 :k3] [v1 v2 v3])))
所以你可以这样写:
(sql/with-connection mysql-db (let [coll-to-insert (map (partial zipmap [:name :appearance :cost]) [["Apple" "rosy" 24] ["Orange" "round" 49] ["Orange" "round" 49] . . . ])] (apply (partial sql/insert-records :fruit) coll-to-insert)))
添加回答
举报
0/150
提交
取消