Phil
Phil

Reputation: 3149

In Clojure, what happens when you call sql/with-connection within another sql/with-connection?

(sql/with-connection *db-atom* (insert-data value1 value2)
 (sql/with-connection *db-atom* (read-tuple-as-map)))

From the above example, does the nested sql/with-connection open a new connection to the DB? Or does it use the one that was created earlier?

Upvotes: 1

Views: 296

Answers (1)

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91554

I would in general recommend using clojure.java.jdbc instead of clojure.contrib.sql because the latter is not supposed to work with clojure newer than 1.2.0.

in clojure.java.jdbc with-connection uses binding to add the connection to a map of connections in the db var for any wrapped calls, so the second one will overwrite the frist one.

from: jdbc.clj

(defn with-connection*
  "Evaluates func in the context of a new connection to a database then
  closes the connection."
  [db-spec func]
  (with-open [^java.sql.Connection con (get-connection db-spec)]
    (binding [*db* (assoc *db* :connection con :level 0 :rollback (atom false))]
      (func))))

Upvotes: 2

Related Questions