David Williams
David Williams

Reputation: 8654

Clojure JDBC: How to Use Pooled Connection for Query

I am following this tutorial on connection pooling using c3p0. https://github.com/clojure/java.jdbc/blob/master/doc/clojure/java/jdbc/ConnectionPooling.md

Then I attempt to run a query with the connection:

(let [db (myapp.db/connection)]
    (jdbc/with-connection db)
        (jdbc/with-query-results rs ["select * from foo"]
            (doseq [row rs]
                (println row)))))

But get this exception

Exception in thread "main" java.lang.IllegalArgumentException: db-spec {:connection nil, :level 0, :legacy true} is missing a required parameter
    at clojure.java.jdbc$get_connection.invoke(jdbc.clj:221)
    at clojure.java.jdbc$with_query_results_STAR_.invoke(jdbc.clj:980)
    at myapp.db_test$eval604.invoke(myapp_test.clj:12)
    at clojure.lang.Compiler.eval(Compiler.java:6619)

According to the tutorial, here is my myapp.db

(def specification {
    :classname "com.mysql.jdbc.Driver"
    :subprotocol "mysql"
    :subname "//localhost:3306/test"
    :user "root"
})

(defn pooled-data-source [specification]
    (let [datasource (ComboPooledDataSource.)]
        (.setDriverClass datasource (:classname specification))
        (.setJdbcUrl datasource (str "jdbc:" (:subprotocol specification) ":" (:subname specification)))
        (.setUser datasource (:user specification))
        (.setPassword datasource (:password specification))
        (.setMaxIdleTimeExcessConnections datasource (* 30 60))
        (.setMaxIdleTime datasource (* 3 60 60))
        {:datasource datasource}))

(def connection-pool
    (delay
        (pooled-data-source specification)))

(defn connection [] @connection-pool)

Thanks in advance!

Upvotes: 3

Views: 2111

Answers (1)

noisesmith
noisesmith

Reputation: 20194

jdbc/with-connection takes the commands you want to run in that connection as arguments, after the spec. You are running no commands in the context with-connection creates, and running everything outside it, where the db connection is not bound.

try this version:

(let [db (myapp.db/connection)]
  (jdbc/with-connection db
    (jdbc/with-query-results rs ["select * from foo"]
        (doseq [row rs]
            (println row))))))

Upvotes: 5

Related Questions