tags:

views:

1865

answers:

1

Assumption: you already have both Clojure and MySQL running on your machine.
How do you make them talk?

+15  A: 

Assumption: you already have both Clojure and MySQL running on your machine.

  1. checkout and build clojure-contrib:

    git clone git://github.com/richhickey/clojure-contrib.git
    cd clojure-contrib
    build
    

    Put the resulting clojure-contrib.jar on your CLASSPATH.

  2. Download MySQL Connector/J and put the mysql-connector-java-5.1.7-bin.jar on your CLASSPATH

    You might have to run your JVM with these arguments:

    -Djdbc.drivers=com.mysql.jdbc.Driver
    
  3. Determine the connection URL of your MySQL database

    For example, if you are running MySQL under MAMP then the URL that you would use in JDBC will look something like:

    conn = DriverManager.getConnection
            ("jdbc:mysql://localhost:8889/db_name?user=root&password=root")
    

    The url is broken down into these components:

    • protocol: jdbc:
    • subprotocol: mysql
    • db-host: localhost
    • db-port: 8889
    • username
    • password
  4. Make this clojure script, modify the database connection parameters to match your URL, save as test.clj, compile and run.

    (use 'clojure.contrib.sql)               ;;' satisfy prettify
    
    
      (let [db-host "localhost"
            db-port 8889
            db-name "db_name"]
        (def db {:classname "com.mysql.jdbc.Driver"
               :subprotocol "mysql"
               :subname (str "//" db-host ":" db-port "/" db-name)
               :user "root"
               :password "root"})
        (with-connection db
          (with-query-results rs ["select * from languages"]
            (dorun (map #(println (:language :iso_code %)) rs)))))
    
    
    
        ; rs will be a sequence of maps,
        ; one for each record in the result set.
    

    NB This code was adapted from similar code written by Mark Volkmann to access a Postgres database from Clojure

devstopfix
The comment (;;' ignore) on the first line is not a required part of the source code - it was added to preserve the syntax colouring of the Clojure source.
devstopfix
Step 1 is now: git clone git://github.com/richhickey/clojure-contrib.git
Notice that you probably won't be able to connect directly to a remote server, so it might be a good idea to port forward some random local port to the server with something like `ssh -L 1234:localhost:3306 user@remoteserver`. Also, check GNU Screen to make it easier to deal with multiple terminals.
konr