Reputation: 57
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?
Upvotes: 0
Views: 635
Reputation: 6956
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))
Upvotes: 1
Reputation: 1107
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)
Upvotes: 1