While answering
this question on stackoverflow about
do-prepared I wanted to show the way to do multiple queries with the same prepared statement (batch select). I thought this is possible in Java, but in clojure.java.sql I ran into several problems. Granted that given a properly parameterized query the database should be able to optimize this automatically by using the execution plan from the cache, it might give an extra bit of performance by stating it up front.
So I set out to test if that was true, but without much success
Here's my first attempt:
(j/with-db-connection[c datasource]
(let [ps (j/prepare-statement c "SELECT count(*) from person where left(name,1)=?")]
(doall (map #(j/query c [ps %]) ["a" "b"]))))
ClassCastException clojure.lang.PersistentHashMap cannot be cast to java.sql.Connection clojure.java.jdbc/prepare-statement (jdbc.clj:454)
This is because
prepare-statement seems to expect a true connection, not the datasource map. All other attempts to wrangle a connection into with-db-connection ended up in other errors.
(j/with-db-transaction [c (j/get-connection datasource)]
(let [ps (j/prepare-statement c "SELECT count(*) from person where left(name,1)=?")]
(doall (map #(j/query c [ps %]) ["a" "b"]))))
IllegalArgumentException No implementation of method: :get-level of protocol: #'clojure.java.jdbc/Connectable found for class: com.microsoft.sqlserver.jdbc.SQLServerConnection clojure.core/-cache-protocol-fn (core_deftype.clj:544)
Since
query accepts a prepared statement instead of a string, I thought this should be possible without having to implement a query equivalent of
do-prepared.
Is there something I overlooked ?