[英]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
))
你必須從with-query-results
宏中實際返回一些東西。 因為seq綁定到results
是懶惰的,讓我們消耗它:
(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的引擎蓋下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.