原帖地址:http://java.ociweb.com/mark/clojure/article.html#Databases
作者:R. Mark Volkmann
译者:RoySong
数据库
Clojure Contrib 中的sql库简化了对关系型数据库的访问,它支持事务提交回滚、预声明、创建和删除表、插入
更新删除记录和运行条件查询。下面的例子连接到一个Postgres数据库并运行了查询。注释中增加了对mysql数据库
的支持。
(use 'clojure.contrib.sql)
(let [db-host "localhost"
db-port 5432 ; 3306
db-name "HR"]
; The classname below must be in the classpath.
(def db {:classname "org.postgresql.Driver" ; com.mysql.jdbc.Driver
:subprotocol "postgresql" ; "mysql"
:subname (str "//" db-host ":" db-port "/" db-name)
; Any additional map entries are passed to the driver
; as driver-specific properties.
:user "mvolkmann"
:password "cljfan"})
(with-connection db ; closes connection when finished
(with-query-results rs ["select * from Employee"] ; closes result set when finished
; rs will be a non-lazy sequence of maps,
; one for each record in the result set.
; The keys in each map are the column names retrieved and
; their values are the column values for that result set row.
(doseq [row rs] (println (row :lastname))))))
clj-record库中提供了持久化的API,这个是从ROR的 ActiveRecord库获得灵感的。要获得更多的信息,请访问
http://github.com/duelinmarkers/clj-record/tree/master 。

本文介绍如何使用ClojureContrib中的SQL库简化关系型数据库的操作,包括事务管理、表的增删改查等,并通过示例展示了如何连接PostgreSQL数据库及进行查询。

被折叠的 条评论
为什么被折叠?



