Ertuğrul Çetin
Ertuğrul Çetin

Reputation: 5231

How to do batch jdbc/insert! and jdbc/update! using postgresql in Clojure?

I was trying to do batch insert and update in Clojure but I'm having some problems.

Libraries that I use are: clojure.java.jdbc and postgresql.

There are some examples on the internet but I could not make it working, I ended up getting exceptions like this:

CompilerException java.sql.BatchUpdateException: Batch entry 0 INSERT INTO person ( data, age ) VALUES ( 'ertu', '24' ) was aborted. Call getNextException to see the cause.

or

CompilerException clojure.lang.ArityException: Wrong number of args (6) passed to: jdbc/db-do-prepared

I'm trying to pass maps or vectors but it does not work so far.

Could you provide some concrete examples that clojure.java.jdbc/insert! and clojure.java.jdbc/update! work?

Also found this question but did not understand what (first stmts) and (rest stmts) are.

Upvotes: 0

Views: 567

Answers (1)

Alejandro C.
Alejandro C.

Reputation: 3801

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

(jdbc/db-do-commands db-spec
  (ddl/create-table :fruit
    [:name "varchar(16)" "PRIMARY KEY"]
    [:appearance "varchar(32)"]
    [:cost :int "NOT NULL"]
    [:unit "varchar(16)"]
    [:grade :real]))
;; -> (0)


(jdbc/insert! db-spec :fruit
  nil ; column names omitted
  ["Red Delicious" "dark red" 20 "bushel" 8.2]
  ["Plantain" "mild spotting" 48 "stalk" 7.4]
  ["Kiwifruit" "fresh"  35 "crate" 9.1]
  ["Plum" "ripe" 12 "carton" 8.4])

Upvotes: 0

Related Questions