2015-08-22 19 views
1

我使用使用Clojure一個H2數據庫。我做了一個表格,並把一些數據,這樣選擇將「CLOB:」到文本Clojure中

(j/create-table :locations 
    [:id "bigint primary key auto_increment"] 
    [:title "varchar (255)"] 
    [:part "clob"]) 

    (j/insert-records :locations 
    {:title "Steven Gerrard: I'm not the new Beckham" :part "He might not have the Becks appeal -- but Steven Gerrard says he's ready to light up Hollywood in his own way..."})) 
    ) 
    ) 

然後我選擇的數據

(defn newest [] 
(database/mysql-db) 
(let [results (j/with-connection db-spec 
        (j/with-query-results res 
        ["select id, title, part from locations"] 
        (doall res)))] 
    results)) 

而且我用了一個clostache頁面

<div class="container"> 
    <sections> 
     {{#newest}} 
      <p style="padding-bottom: 15px;">{{title}}<p> 
      <p style="padding-bottom: 15px;">{{part}}<p> 
     {{/newest}} 
    </sections> 
    </div> 

上的數據在頁面我得到

Steven Gerrard: I'm not the new Beckham 

clob0: 'He might not have the Becks appeal -- but Steven Gerrard says he''s ready to light up Hollywood in his own way...' 

我該怎麼辦卸下連接到我的數據庫中的文本字符串clob0:?出現這種情況,即使我用text,而不是clob在我的數據庫中的部分列。

回答

0

我刪除了clob:有:

(defn clob-to-string [row] 
    (assoc row :text (with-open [rdr (java.io.BufferedReader. (.getCharacterStream (:text row)))] 
    (apply str (line-seq rdr))))) 

(defn newest [] 
(database/mysql-db) 
(j/query db-spec 
      ["select id, title, text from news"] 
      :row-fn clob-to-string 
    )) 
1

的 'clob0:' 前綴是不實際連接到數據庫中的數據。

你得到這個的原因是因爲ResultSet爲列「part」返回類java.sql.Clob的實例(對於CLOB和TEXT數據類型,它們實際上是synonyms)。

它不是通過toString()方法爲CLOB轉換爲字符串適當的方式,實現自由返回任何人類可讀的形式。正確的方法可以在other answers找到。

1

您可能已經注意到,新的生產線得到由上述輸了...像這樣增加了它們放回...

(defn clob-to-string [clob] 
     "Turn an Clob into a String, with new new lines" 
    (with-open [rdr (java.io.BufferedReader. (.getCharacterStream clob))] 
     (let [lseq (line-seq rdr) 
      butlast-line (butlast lseq) 
      butlast-line-mapped (map (fn [l] (str l "\n")) butlast-line) 
      last-line (last lseq) 
      all-lines-with-newline (concat butlast-line-mapped last-line) 
      ] 
     (apply str all-lines-with-newline) 
     )))