Saturday, January 31, 2009

Clojure and MySQL, continued

I've been working through the Data Access section of the Clojure in the Wild chapter in Stuart Halloway's Programming Clojure. Here's a MySQL version of the last-created-id form:

(defn last-created-id
  "Extract the last created id. Must be called in a transaction
  that performed an insert. MySQL version."
  []
  (:last_created_id (first (sql-query "select LAST_INSERT_ID() as last_created_id"))))


Thursday, January 29, 2009

Clojure and MySQL

Here's the magical connection incantation to get Clojure and MySQL talking:

(def *db* {:classname "com.mysql.jdbc.Driver"
  :subprotocol "mysql" :subname "//your-server/your-db"
  :user "your-user" :password "your-password"})


Assumptions - you're using
  • Stephen C. Gilardi's clojure.contrib.sql library, and

  • MySQL's Connector/J JDBC driver, with mysql-connector-java-5.1.7-bin.jar in your Clojure classpath.
Clojure is elegant. It's from the future, with features like support for software transactional memory. Meantime, it's a close personal friend of Java, so it plays well with more mundane tools. I get a buzz when that happens. I've flirted with lisps before, but this one feels like a keeper.

Incidentally, the Connector/J license defaults to GPL, so it may contaminate your application like ice-nine. Hail Bokonon!