next.jdbc library for SQL with Clojure
seancorfield/next.jdbc is the defacto wrapper for JDB databases from Clojure. next.jdbc getting started guide is very detailed.
Using next.jdbc is simple and requires only a few steps
- require the next.jdbc library
- define a database specification (hash-map of database details)
- create a connection (or use connection pool)
- execute SQL statements (individual, batch, transaction)
next.jdbc supersedes clojure.java.jdbc
seancorfield/next.jdbc supersedes clojure.java.jdbc
which used to be the defacto library for database backed projects. next.jdbc is faster and exposes a more modern API design (according to the author of clojure.java.jdbc). Migration from clojure.java.jdbc is documented on the next.jdbc repository
Summary of using next.jdbc
The primary SQL execution API in next.jdbc is:
plan
yields an IReduceInit that, when reduced, executes the SQL statement and then reduces over the ResultSet with as little overhead as possible.
execute!
-- executes the SQL statement and produces a vector of realized hash maps, that use qualified keywords for the column names, of the form :
execute-one!
-- executes the SQL or DDL statement and produces a single realized hash map. The realized hash map returned by execute-one! is Datafiable and thus Navigable.
In addition, there are API functions to create PreparedStatements (prepare) from Connections, which can be passed to plan, execute!, or execute-one!, and to run code inside a transaction (the transact function and the with-transaction macro).
Using connections effectively
Use the with-open
Clojure core function to reuse connections and ensure they are cleaned up correctly:
next.jdbc
uses raw Java JDBC types
(let [my-datasource (jdbc/get-datasource {:dbtype "..." :dbname "..." ...})]
(with-open [connection (jdbc/get-connection my-datasource)]
(jdbc/execute! connection [...])
(reduce my-fn init-value (jdbc/plan connection [...]))
(jdbc/execute! connection [...])))