funcool / clojure.jdbc

JDBC library for Clojure
http://funcool.github.io/clojure.jdbc/latest/
Apache License 2.0
105 stars 26 forks source link

How to execute! multiple SQL commands over a connection? #15

Closed theronic closed 10 years ago

theronic commented 10 years ago

How can I reuse the same connection to run multiple SQL commands? When I eval my (build-schema) defined below, I get the error:

java.sql.SQLException: You can't operate on a closed Connection!!!

Here is a mock schema using SQLingvo:

(def my-schema [
    (sql (create-table :users
                  (column :id :uuid :primary-key? true)
                  (column :email :text)))
    (sql (create-table :publishers
                  (column :id :uuid :primary-key? true)
                  (column :name :text :not-null? true)))])

Here is my build-schema function that doseq's over my schema:

(defn build-schema []
  (let [conn (make-connection dbspec)]
    (tx/with-transaction conn
      (with-catch
        (doseq [[cmd] my-schema]
          (execute! conn cmd))
        (.close conn)))))
theronic commented 10 years ago

Ah, sorry I had to put the (.close conn) outside the tx/with-transaction:

(defn build-schema []
  (let [conn (make-connection dbspec)]
    (with-catch
    (tx/with-transaction conn
        (doseq [[cmd] my-schema]
          (execute! conn cmd)))
        (.close conn))))
niwinz commented 10 years ago

You also can use with-open clojure macro :D

(with-open [conn (make-connection dbspec)]
  your code here...)

You can see few options to open a connection here: http://niwibe.github.io/clojure.jdbc/#_creating_a_connection