I couldn't figure out how to do this with the included functions/
macros in clojure.contrib.sql so I massaged with-results and do-
prepared together to get this macro (with supporting fn), which seems
to work. Useful addition for contrib.sql?

;; query-with-results should work just like with-results, only
parameterizing query variables.

(defn- get-ps
  "Generate a prepared statement with a vector of parameters to
support the query."
  [sql params]
  (let [ps (.prepareStatement (connection) sql)]
    (doseq [[index value] (map vector (iterate inc 1) params)]
      (.setObject ps index value))
    ps))

(defmacro query-with-results
  "Executes a query with parameterized results and then evaluates body
with results bound to a seq of
  the results.

  Example usage: (with-connection db (query-with-results res \"select
* from mytable
                         where name = ? or id = ?\" [\"Foo\" 3]
(println res)))"
  [results sql params & body]
  `(with-open [stmt# (get-ps ~sql ~params)
               rset# (.executeQuery stmt#)]
     (let [~results (resultset-seq rset#)]
       ~...@body)))

I would have liked to eliminate the helper function and just get this
all into the macro, but I burned my allotted time on it before I got
that working...

-Greg

On Jan 9, 5:05 pm, Greg Harman <ghar...@gmail.com> wrote:
> Would someone mind posting an example of a parameterized query using
> clojure.contrib.sql? There are examples in the source of non-
> parameterized queries, and do-prepared is used to parameterize values
> for inserts, but I can't seem to get my form quite right for a query.
>
> thanks,
> Greg
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To post to this group, send email to clojure@googlegroups.com
To unsubscribe from this group, send email to 
clojure+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to