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

Dav*_*ams 3 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)))))
Run Code Online (Sandbox Code Playgroud)

但是得到这个例外

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)
Run Code Online (Sandbox Code Playgroud)

根据教程,这是我的 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)
Run Code Online (Sandbox Code Playgroud)

提前致谢!

noi*_*ith 5

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

试试这个版本:

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