Use a database with Clojure

Viewed 18093

What methods to use a database from Clojure are there?

I know from Clojure you can do anything you can with Java, but that means that I may end up using something overly complicated (like Hibernate) which clashes with Clojure simplicity. Any recommendations or comments?

12 Answers

clojure-contrib has an sql library which is a thin wrapper around JDBC (java.sql.DriverManager). The test file that comes with it has some examples of its usage.

If you are open to using a Java library but want something that embraces simplicity, perhaps you'll like Persist. It'll only take you 10 minutes to have a look and see if it fits your needs.

I've used Berkeley DB for a simple key/value database in Clojure. See here.

Firstly, Import libraries from

 (ns clojureexercise.test
    (:require [clojure.java.jdbc :as sql])) ;;sql will alias used further in code to access java jdbc feature.

Secondly, the function below allows you to connect MySQL server. Like in Java, we declare Database variable to start DB, here it is the same way we have to define Database connectivity and in below code you can see db variable is defined in the dbconnect function. db variable will be used further in running queries.

(defn dbconnect []
  (def db{   
         :classname "com.mysql.jdbc.Driver" 
         :subprotocol "mysql"
         :subname "//127.0.0.1:3306/testdb" ;;testdb is the name of database
         :user "root"
         :password "password"}))

Now,

;;Inserting Data into Database 
;;Table Name is patientinfo, consist columns {id, firstname, lastname, birthdate, gender}
 (defn insertdata []
  (sql/insert! db :patientinfo                    ;;used sql alias and db variable to insert data into table 
  {:id 1 :firstname "Satyam" :lastname "Ramawat" 
   :birthdate "1/1/2018" :gender "Male" }))

I will elaborate this more:

sql/insert! db :patientinfo

sql will enable insert query functionality and db will allow the system to understand on which table the record has to be inserted of which database connection.

Related