如何在Clojure中访问SQLite数据库?

时间:2009-09-26 01:15:27

标签: 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
    ))

1 个答案:

答案 0 :(得分:11)

您必须实际从with-query-results宏内返回一些内容。因为绑定到results的seq是懒惰的,让我们消耗它:

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

这是使用clojure.contrib.sql时的常见模式,不依赖于SQLite JDBC适配器。

顺便说一下,我从来没有必须手动执行(Class/forName driver-class-str),这显然是你的Java习惯。驱动程序被加载到contrib.sql引擎的某个地方。

相关问题