首页 > clojure java.jdbc 如何批量插入数据库

clojure java.jdbc 如何批量插入数据库

在 https://github.com/clojure/java.jdbc 上面有关于clojure插入数据库的示例 ,那么,若我想批量插入,该怎么操作?是这样拼多个?还是有更简便的写法?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}
    .
    .
    .  
  ))

一般来说可以直接使用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)))

最后推荐一个东西,叫做korma,官网是http://www.sqlkorma.com,是一个比较方便的sql封装库~

【热门文章】
【热门文章】