Clojure JDBC:如何使用池化连接进行查询

时间:2013-06-05 21:03:04

标签: mysql jdbc clojure c3p0

我正在使用c3p0关注连接池的本教程。 https://github.com/clojure/java.jdbc/blob/master/doc/clojure/java/jdbc/ConnectionPooling.md

然后我尝试使用连接运行查询:

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

但是得到这个例外

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)

根据教程,这是我的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)

提前致谢!

1 个答案:

答案 0 :(得分:4)

jdbc / with-connection在规范之后将您想要在该连接中运行的命令作为参数。您在上下文中没有运行任何命令 - 连接创建,并运行其外部的所有内容,其中未绑定数据库连接。

试试这个版本:

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