简体   繁体   English

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

[英]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. 你必须从with-query-results宏中实际返回一些东西。 And because the seq bound to results is lazy, let's consume it: 因为seq绑定到results是懒惰的,让我们消耗它:

(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. 这是使用clojure.contrib.sql时的常见模式,不依赖于SQLite JDBC适配器。

Btw I've never had to do (Class/forName driver-class-str) manually, this is clearly your Java habit. 顺便说一句,我从来没有必须手动执行(Class/forName driver-class-str) ,这显然是你的Java习惯。 Driver is loaded somewhere under the hood of contrib.sql. 驱动程序被加载到contrib.sql的引擎盖下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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