(return to home)

clojure.jdbc - JDBC for Clojure

This is a young library what intends be a real alternative to the current clojure contrib library: clojure.java.jdbc.

Why? The answer to this querstion can be simple. The first reason for existente of clojure.jdbc is thar a original library has a very unintuitive api and documentation is realy unexistent. You can read other reasons on the FAQ page.

This is a little list of clojure.jdbc project goals:

  • Explicit is better than implicit.
  • Readability counts.
  • Should be concise and intuitive for humans.
  • Well documented.
  • Open to contributions.
  • More permisive license.

Gettings started making a query

The simplest way to see how it works, is seeing a one basic example. In this case, we go to create a connection and execute a query.

(require '[jdbc.core :refer [with-connection query]])

(def dbspec {:classname "org.postgresql.Driver"
             :subprotocol "postgresql"
             :subname "//localhost:5432/dbname"
             :user "username"
             :password "password"})

(with-connection dbspec conn
  (let [result (query conn "SELECT 1 + 1 as foo;")]
    (println result)))

;; -> [{:foo 2}]

with-connection is a helper idiomatic macro that hides a real implementation and resource management, but if you want more control over resource management, you can use make-connection function instead:

(require '[jdbc.core :refer [make-connection query]])

(with-open [conn (make-connection spec)]
  (let [result (query conn "SELECT 1 + 1 as foo;")]
    (println result)))

Similar code using a clojure.java.jdbc (proposed by the author of clojure.java.jdbc on the clojure mailing list):

(require '[clojure.java.jdbc :as jdbc])

(def dbspec {:classname "org.postgresql.Driver"
             :subprotocol "postgresql"
             :subname "//localhost:5432/dbname"
             :user "username"
             :password "password"})

(with-open [con (jdbc/get-connection db-spec)]
  (let [connected  (jdbc/add-connection db-spec con)
        result     (jdbc/query connected ["SELECT 1 + 1 as foo;"])]
    (println result)))

clojure.jdbc is mainly designed for be used by humans with more clear and intuitive api than clojure.java.jdbc.

You can read more about all features and more examples on project documentation page and access to source code on Github.

Comments