Assumption: you already have both Clojure and MySQL running on your machine.
How do you make them talk?
views:
1865answers:
1Assumption: you already have both Clojure and MySQL running on your machine.
checkout and build clojure-contrib:
git clone git://github.com/richhickey/clojure-contrib.git cd clojure-contrib buildPut the resulting clojure-contrib.jar on your CLASSPATH.
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.DriverDetermine 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
- protocol:
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