30

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

4 Answers 4

29

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
15

This is a lein-friendly answer, with much guidance from this blog by Nurullah Akkaya:

  1. add dependencies to your project.clj:

    (defproject clojql "1.0.0-SNAPSHOT"
      :description "FIXME: write description"
      :dependencies [[org.clojure/clojure "1.2.1"]
                     [org.clojure/clojure-contrib "1.2.0"]   ;; for clojure.contrib.sql
                     [org.clojure/java.jdbc "0.0.6"]         ;; jdbc 
                     [mysql/mysql-connector-java "5.1.6"]])  ;; mysql driver
    
  2. run lein deps from the command line to grab the dependencies

  3. specify your connection information in a map:

    user=> (use 'clojure.contrib.sql)
    nil
    user=> (def db {:classname "com.mysql.jdbc.Driver" 
                    :subprotocol "mysql" 
                    :subname "//localhost:3306/nmr" 
                    :user "root"})
    
  4. use with-connection and with-query-results macros (& others):

    user=> (with-connection db (with-query-results rs ["select * from sometable"] (count rs)))
    667
    

steps 3 & 4 can either be from the repl (lein repl to start it) or within normal source code

1 Comment

Thanks! By the way, the latest "stable" versions at this time are 1.4.0 for clojure, 0.2.3 for java.jdbc, and 5.1.22 for mysql-connector-java. clojure-contrib is no longer needed and clojure.contrib.sql is now part of java.jdbc. See github.com/clojure/java.jdbc for an example.
9

As of 2016:

using Leiningen, add dependencies inside project.clj:

:dependencies [[org.clojure/clojure "1.8.0"]
               [org.clojure/java.jdbc "0.4.2"]
               [mysql/mysql-connector-java "5.1.38"]]

require database connector inside namespace definition:

(ns name.space
  (:require [clojure.java.jdbc :as j]))

define database connection:

(def db-map {:subprotocol "mysql"
             :subname "//localhost:3306/SCHEME"
             :user "DB_USER"
             :password "DB_USER_PASS"})

query the database:

(j/query db-map ["SELECT * FROM table"])

find more examples at http://clojure-doc.org/articles/ecosystem/java_jdbc/using_sql.html

Comments

4

If you want some syntactic sugar, you can try Korma.

Docs

Github

(use 'korma.db)
(defdb db (postgres {:db "mydb"
                     :user "user"
                     :password "dbpass"}))

(use 'korma.core)
(defentity users)


(select users)
;; executes: SELECT * FROM users


(select users
  (where (or (= :usersname "chris")
             (= :email "[email protected]"))))
;; executes: SELECT * FROM users WHERE (users.usersname = 'chris' OR users.email = '[email protected]')

2 Comments

That's not really mysql though.
@Ven, While the defdb in the snippet above indeed points to Postgres, the documentation covers MySql amongst other databases. See here: sqlkorma.com/docs#db Maybe the code snippet can be updated to have a better correlation with the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.