代码之家  ›  专栏  ›  技术社区  ›  Bill

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

  •  4
  • Bill  · 技术社区  · 17 年前
    (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 回复  |  直到 17 年前
        1
  •  11
  •   Wojciech Kaczmarek    16 年前

    你必须从内部返回一些东西 with-query-results 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引擎盖下的某个位置。

    推荐文章