clojure学习点滴2

来源:互联网 发布:淘宝一千零一夜2 编辑:程序博客网 时间:2024/06/05 20:09

1 clojure 与 数据库操作 korma

   (:use [korma.db])    (:use [korma.core])

  (def db (postgres {:db "test" 
                       :user "lizd"
                       :password "lizd"
                       ;; optional keys
                       :host "localhost"
                       :port "5432"
                       :delimiters ""}))

 (defdb pg db)
 (defentity pgbooks (table :books) (database pg)) ;; 当有多个数据库连接时,需要(database pg)表达式

2 clojure 与 pgsql9.3 的json

(jd/insert! pgsql-db :jsontest {:id 4 :data (doto (PGobject.) (.setType "json") (.setValue (slurp "http://localhost:8082/product/1001"))) })

(exec-raw ["insert into jsontest(id, data) values(?, to_json(?))" [2, (slurp "http://localhost:8080/wzh-04/fpcx")]] :results))

-- 读取json的操作  (def d (:b_data (first (select pgbooks (limit 1) (offset 2)))))  (class d)  org.postgresql.util.PGobject  (.getType d)  "json"  (.getValue d)  "{ \"name\": \"Book the Third\", \"author\": { \"first_name\": \"Jim\", \"last_name\": \"Brown\" } }" (require '[cheshire.core :as json])  (json/decode (.getValue d))  {"name" "Book the Third", "author" {"first_name" "Jim", "last_name" "Brown"}}

(defmulti decode-pgobject  (fn [pgobject] (keyword (.getType pgobject))))(defmethod decode-pgobject :citext [pgobject]  (.getValue pgobject))(defmethod decode-pgobject :json [pgobject]  (if-let [value (.getValue pgobject)]    (json/read-str value :key-fn keyword)))(defmethod decode-pgobject :default [pgobject]  pgobject)(decode-pgobject d)     => {:name "Book the Third", :author {:first_name "Jim", :last_name "Brown"}}


0 0
原创粉丝点击