如何在Clojure中执行批量SQL更新查询?

时间:2018-04-02 16:02:48

标签: jdbc clojure

如何使用引导下的预准备语句作为单个批量调用执行以下对千行的查询?

(clojure.java.jdbc/execute! db ["UPDATE person SET zip = ? WHERE zip = ?" 94540 94546])

clojure/jdbc是否具有适当的功能或其他内容?

2 个答案:

答案 0 :(得分:4)

找到答案。适用的功能是clojure.java.jdbc/db-do-prepared,启用了:multi?密钥。

(clojure.java.jdbc/db-do-prepared db
  ["UPDATE person SET zip = ? WHERE zip = ?"
   [94540 94546]
   [94541 94547]
   ...
  ] 
  {:multi? true})

答案 1 :(得分:0)

这是我为我的一个项目做的方式:

(require '[clojure.java.jdbc :as sql])


(defn- db-do-cmd
  [command]
  (sql/db-do-commands @db-url command))


(defn- create-update-phone-sql
  [{:keys [fname lname dob phone]}]
  (let [where-init (format "UPDATE person SET phone = %s WHERE " (escape-quote-and-null phone))
        where-rest (apply str (interpose " AND " [(str "person.dob" (escape-quote-and-null-for-where dob))
                                                  (str "person.fname" (escape-quote-and-null-for-where fname))
                                                  (str "person.lname" (escape-quote-and-null-for-where lname))]))]
    (str where-init where-rest)))


(defn batch-update!
  [coll]
  (db-do-cmd (map create-update-phone-sql coll)))