3

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))))

3 Answers 3

3

[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.

Sign up to request clarification or add additional context in comments.

Comments

3
(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))) ))))

2 Comments

Zmila, I wanted to know about a BLOB, not a CLOB.
Is there a better way to do this 10 years later? I'm getting Clob instances back for columns specified as "text" or "longtext" in ddl. I'd love to just get strings back without having to implement my own later around all my sql queries.
0
(defn blob-to-byte [blob]
    (let [ary (byte-array (.length blob))
          is (.getBinaryStream blob)]
    (.read is ary)
    (.close is)
    ary))

(j/query db/real-db ["select blob from table"]
         {:row-fn #(->> % :blob blob-to-byte)}))

1 Comment

From Review: Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to the OP as well as other users also with similar issues. See: How do I write a good answer?. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.