问题
per the following link http://clojure.github.io/java.jdbc/#clojure.java.jdbc/insert!
this function has parameters as
(insert! db-spec table col-name-vec col-val-vec & col-val-vecs :transaction? true :entities identity)
So it accept multiple vectors to be inserts as multiple rows.
But if I have a list of vectors, and how to pass it to this function?
(def rows (repeat 10 [ 1 2]))
(clojure.jdbc/insert mydb test_table [:a :b] rows) ;; this doesn't work as rows is a list of vector
;; I could use map to insert one by one but that's slow,
;; so how to convert rows into multiple vector?
;;I am think of apply function but don't know how to use it here.
回答1:
I think you want to use apply
:
(def rows (repeat 10 [ 1 2]))
(apply clojure.jdbc/insert! mydb test_table [:a :b] rows)
In general, apply
is useful in cases where you have a collection containing values you want to pass as parameters to a function.
回答2:
The apply solution already suggested is the standard way to explode a list of values to be arguments in a function call.
However, if performance is your main concern, it will be important to configure jdbc to use a connection pool and to make sure you have the correct level of granularity on your transactions.
I found it very useful to go through the tests in the java.jdbc repository on github. Highly recommend it if you want to get more familiar with how to use the library.
Finally, there can also be significant differences depending on the backend database (and underlying jdbc connector) you are using. In some cases, it may be necessary to look at both the java.jdbc implementation code as well as the driver functionality to understand how the clojure jdbc functions map to the underlying jdbc driver. This can give you clear ideas on how to best call the java.jdbc clojure functions. I found this r3eally useful when I wanted to use this library with an Oracle databse and call stored procedures. Of course, not a recommended things to do as you make very fragile code (while this approach solved my problem originally, the library moved on and as my code was not being polite, it broke - this was OK as I only needed this level of functionality for a short period).
来源:https://stackoverflow.com/questions/27800061/how-to-pass-a-list-of-vector-to-clojure-jdbc-insert-in-closure