Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure read Blob from database

I need to read bytes from this Blob. I'm trying the following but I'm getting this exception: oracle.sql.BLOB cannot be cast to [B

(defn select-test2[]
  (clojure.contrib.sql/with-connection db
    (with-query-results res ["SELECT my_blob from some_table"] (doall res))))

(defn obj [byte-buffer]
  (if-not (nil? byte-buffer)
    (with-open [object-in (ObjectInputStream.
                            (ByteArrayInputStream. byte-buffer))]
      (.readObject object-in))))

(obj (:my_blob (first (select-test2))))
like image 218
aQ123 Avatar asked Jan 28 '26 13:01

aQ123


2 Answers

[B is the "class" of a byte array:

user=> (type (byte-array 0))
[B

So there's a place in your code that is expecting a byte array, but it's being given an oracle.sql.Blob instance. My bet is that :my_blob is giving you a Blob; when you pass byte-buffer (which is the Blob) to the ByteArrayInputStream constructor, you get the exception.

Look up the javadocs for oracle.sql.Blob to see how to extract a byte array or input stream from it.

like image 155
Alex Taggart Avatar answered Jan 30 '26 06:01

Alex Taggart


(ns test-jdbc
  (:use clojure.contrib.sql))

; read clob with BufferedReader
(defn clob-to-string [clob]
  (with-open [rdr (java.io.BufferedReader. (.getCharacterStream clob))]
    (apply str (line-seq rdr))))

; read first CLOB 
(defn get-meta-by-id [db id]
  "read META_COL from MY_TABLE by given id"
  (with-connection db
    (transaction ;; need to be inside a transaction
      (with-query-results rs 
        ["select META_COL from MY_TABLE where ID = ? " id]
        (clob-to-string (:meta-col (first rs))) ))))
like image 36
zmila Avatar answered Jan 30 '26 06:01

zmila



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!