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