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

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

最佳答案

您实际上必须从 with-query-results 宏中返回一些内容。因为绑定(bind)到 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 的底层某处。

关于sqlite - 如何在 Clojure 中访问 SQLite 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1480162/

相关文章:

C、如何传递sqlite3数据库句柄

java - 无法返回 Cursor 对象 - close() 从未明确称为错误

java - SQLite 类未找到异常 - 使用 Tomcat 的 Maven 项目

sqlite - 在 Mac 上创建 SQLite3 数据库

scala - Clojure 的 'let' 在 Scala 中等效

ios - sqlite3_prepare_v2 崩溃 - 已经在运行之前的查询

multithreading - 改变 Clojure 的 ref 的线程越多,每个线程的重试率上升得越多?

clojure - 如何在 Clojure 中打印到 STDERR?

ruby - 有没有一种好方法可以让 Ruby 通过某种类型的桥与 Clojure 对话,反之亦然?

java - 在 Clojure 中捕获系统/输出