简体   繁体   中英

How to execute batch SQL update query in Clojure?

How to execute the following query for thousand rows as a single batch call using a prepared statement under the hood?

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

Does clojure/jdbc has an appropriate function or something else for that?

Found the answer. Applicable function is clojure.java.jdbc/db-do-prepared with enabled :multi? key.

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

Here is the way I did it for one of my projects:

(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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM