How to access SQLite database in 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 )) 
+4
source share
1 answer

You should actually return something from the with-query-results macro. And since seq attached to results is lazy, let it 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 bound to the Jite SQLite adapter.

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

+11
source

All Articles