Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access an SQLite database in Clojure?

Tags:

sqlite

clojure

(ns db-example
   (:use [clojure.contrib.sql :only (with-connection with-query-results)] )
   (:import (java.sql DriverManager)))

;; need this to load the sqlite3 driver (as a side effect of evaluating the expression)
(Class/forName "org.sqlite.JDBC")

(def +db-path+  "...")
(def +db-specs+ {:classname  "org.sqlite.JDBC",
                 :subprotocol   "sqlite",
                 :subname       +db-path+})

(def +transactions-query+ "select * from my_table")

(with-connection +db-specs+
  (with-query-results results [+transactions-query+]
    ;; results is an array of column_name -> value maps
    ))
like image 691
Bill Avatar asked Dec 22 '22 08:12

Bill


1 Answers

You have to actually return something from within with-query-results macro. And because the seq bound to results is lazy, let's consume it:

(with-connection +db-specs+  
   (with-query-results results [+transactions-query+]  
     (doall results)))  

This is a common pattern when using clojure.contrib.sql, not tied to the SQLite JDBC adapter.

Btw I've never had to do (Class/forName driver-class-str) manually, this is clearly your Java habit. Driver is loaded somewhere under the hood of contrib.sql.

like image 192
Wojciech Kaczmarek Avatar answered Jan 04 '23 07:01

Wojciech Kaczmarek