0

I am trying to get some text from a database and use it in a function in clojure.

(defn getSelectedText [id]
    (j/query mysql-db
    ["select timesRead, text from news where id=?" id]))

When I println this it shows

( {:timesRead 6, :text "Some text"})

When I try get to get the text from this it just doesn't work.

Do you have any idea how to change the getSelectedText function to get the text I need?

2
  • Isn't it a sequence that consists of one element? Commented Aug 19, 2015 at 10:08
  • Yup, zerkms is right, you're trying to do a get on a collection of one map (record). Commented Aug 19, 2015 at 12:26

2 Answers 2

2

try

(defn getSelectedText [id]
  (:text
    (first
      (j/query mysql-db
      ["select timesRead, text from news where id=?" id]))))

you're getting back a sequences of maps. first gives you the first item in the sequence, so then you have a map. :text says 'give me the value assigned to the :text key in the map'.

A note about retrieving values out of maps: what's interesting is that you can actually do either

(:text my-map)

or

(my-map :text)

(also, the first form works with keywords (which start with the colon :) but not with keys that are strings; the jdbc library generally keywordizes column names for convenience)

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

Comments

1

When the resultset contains more records, you might want to take a look at the :row-fn and :result-set-fn parameters of clojure.java.jdbc/query to prevent copying all the of resultset before the connection is closed.

Processing inside the scope of the query fn / connection in this case would be done like

(defn getSelectedText [id]
  (j/query mysql-db
           ["select timesRead, text from news where id=?" id]
           :result-set-fn first  ;this fn should NOT be lazy
           :row-fn :text))

2 Comments

i agree that using :result-set-fn is a good practice for large datasets. but query does actually return a fully realized sequence, so it's safe to process the results outside/afterward if desired.
Of course, default result-set-fn is doall. Will edit ehen back at a real kb

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.