Saturday, 26 September 2009

Clojure: Getting started with Clojure + Oracle

I had a hard time googling on how to connect clojure to an oracle database using clojure's sql library (i.e. clojure.contrib.sql). In the end I had to look into the code to see how they were contructing the jdbc url. At work, we already have a properties file which contains the driver class and url to connect to oracle via jdbc. The content looks something like this:

DBURL=jdbc\:oracle\:thin\:@localhost\:1655\:ORCL
DRIVER=oracle.jdbc.OracleDriver
DBUSER=john
DBPASSWORD=password

To translate that to a database spec to be used by clojure.contrib.sql, I had this function:

(defn get-db-spec
  [properties]
  (let [classname (.getProperty properties "DRIVER")
        url (.getProperty properties "DBURL")
        user (.getProperty properties "DBUSER")
        password (.getProperty properties "DBPASSWORD")
        groups (next(first (re-seq #"jdbc:(\w+):(.+)" url)))]
    {:classname classname
     :subprotocol (first groups)
     :subname (second groups)
     :url url
     :user user
     :password password}))

It's kinda odd that I had to deconstruct the url and then have the library reconstruct it again. Probably there's a better way to do this, but there are more interesting things to worry about :P

No comments: