3

我正在关注关于使用 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)

提前致谢!

4

1 回答 1

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))))))
于 2013-06-06T16:04:46.977 回答