Skip to content

Instantly share code, notes, and snippets.

@thickey
Last active October 14, 2017 17:10
Show Gist options
  • Save thickey/24d66f3c05567d68fa9a0c55a6013bd6 to your computer and use it in GitHub Desktop.
Save thickey/24d66f3c05567d68fa9a0c55a6013bd6 to your computer and use it in GitHub Desktop.
Handling multiple results from Clojure with SQL the includes temp tables

Handling multiple results from SQL that includes temp tables.

NB! this is using clojure.java.jdbc v0.6.1, as we have performance issues w/ 0.7.x

Although this gist was very helpful when all statements return results, this is what is ultimately needed to properly traverse the intermediate reults that return nothing (e.g. temp tables).

(ns multiple-results
(:require [clojure.java.jdbc :as sql]))
;; snipped from clojure.java.jdbc
(defn set-parameters
"Add the parameters to the given statement."
[stmt params]
(dorun (map-indexed (fn [ix value]
(sql/set-parameter value stmt (inc ix)))
params)))
(defn get-multiple-result-sets
[dbspec cmd params]
(with-open [con (sql/get-connection dbspec)]
(let [stmt (sql/prepare-statement con cmd)]
(set-parameters stmt params)
(.execute stmt)
(loop [results [] ]
(let [result-set (.getResultSet stmt)
results (if result-set
(conj results (into [] (sql/result-set-seq result-set)))
results)]
(if (or (.getMoreResults stmt)
(not= (.getUpdateCount stmt) -1))
(recur results)
results))))))
(defproject multiple-results "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/java.jdbc "0.6.1"]
[com.microsoft.sqlserver/sqljdbc4 "4.0"]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment