Welcome to Clojure

Using Clojure for something Simple

Posted by 11/23/2009

I haven't written anything in a long time. To get things started, I'm posting a tiny fragment of code in a language I'm dabbling in lately, Clojure.

I have several long stories half-written. But every time I think about finishing them I am looking at a daunting task and I just end up doing nothing.

So to get things started again, I'm looking into Clojure lately. I don't know it very well, and am certainly not someone to be consulted about it. But I have to start somewhere you know?

The truth is after programming 14 years or so, I've found that on any sufficiently large project I always end up always wanting the following things from the language I'm using:

  • first class functions
  • currying
  • runtime code templates
  • namespacing
  • asynchronous operations
  • "batteries included"

And Clojure is the first thing I've seen that gives me every one of those.

I've read enough Paul Graham to know there are those that argue that LISP is the greatest language ever. It took me a long time to see it. I didn't understand. The PAIN that is working with any Common Lisp implementation did not help. But Clojure is easy to jump into. And the simple addition of the map as a built-in data structure really won me over.

Here's a very rudimentary, useless thing I wrote which will not in any way convince you to use Clojure. But I have to start somewhere.

I needed to connect to a database and run some sql statements. So I wrote a program to read the the name of a file from the command line and run whatever statement is in the file against the database. It just spits out the results to the command line. Like I said, really nothing worthwhile.

 1 (use 'clojure.contrib.sql)
 2 (use 'clojure.contrib.duck-streams)
 3
 4 (require 'config)
 5
 6 (defn read-sql [filename]
 7   (slurp filename))
 8
 9 (with-connection db
10   (with-query-results rs [(read-sql (second *command-line-args*))]
11     (doseq [x rs](println x))))

sqlrunner.clj

Here's the config file (from the (require 'config) line

1 (def db {:classname "oracle.jdbc.driver.OracleDriver" ; must be in classpath
2          :subprotocol "oracle:thin"
3          :subname "@localhost:1521/database"
4          :user "user"
5          :password "password" })

config.clj

And then something to run it

1 # bin/sh
2 export CLASSPATH=.:../lib/clojure-1.0.0.jar:../lib/clojure-contrib.jar:../lib/ojdbc5.jar
3 java clojure.main test.clj $1 $*

sql.sh

To be Continued...

Comments

Post a comment


Total: 0.08 Python: 0.06 DB: 0.01 Queries: 33