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
提交
取消