Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I connect to a MySQL database from Clojure?

Tags:

mysql

clojure

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

like image 501
devstopfix Avatar asked Mar 05 '09 08:03

devstopfix


People also ask

How do I connect to a MySQL database?

To Connect to a MySQL Database Expand the Drivers node from the Database Explorer. Right-click the MySQL (Connector/J driver) and choose Connect Using.... The New Database Connection dialog box is displayed. In the Basic Setting tab, enter the Database's URL <HOST>:<PORT>/<DB> in the corresponding text field.


1 Answers

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

like image 96
devstopfix Avatar answered Sep 22 '22 03:09

devstopfix