简体   繁体   中英

How do I access an 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
    ))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM