(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
))
Run Code Online (Sandbox Code Playgroud)
Woj*_*rek 11
你必须从with-query-results
宏中返回一些东西.因为seq绑定results
是懒惰的,让我们消耗它:
(with-connection +db-specs+
(with-query-results results [+transactions-query+]
(doall results)))
Run Code Online (Sandbox Code Playgroud)
这是使用clojure.contrib.sql时的常见模式,不依赖于SQLite JDBC适配器.
顺便说一下,我从来不必(Class/forName driver-class-str)
手动操作,这显然是你的Java习惯.驱动程序被加载到contrib.sql的引擎盖下.