Back

SettableParameter (clj)

(source)

protocol

Protocol for setting SQL parameters in statement objects, which can convert from Clojure values. The default implementation just calls `.setObject` on the parameter value. It can be extended to use other methods of `PreparedStatement` to convert and set parameter values. Extension via metadata is supported.

Examples

kit-clj/kit
(ns kit.edge.db.mysql
  (:require
    [next.jdbc]
    [next.jdbc.prepare :as prepare]
    [next.jdbc.result-set :as result-set])
  (:import
    [java.sql Array PreparedStatement Timestamp]
    [java.time Instant LocalDate LocalDateTime]))

(extend-protocol prepare/SettableParameter
  Instant
  (set-parameter [^Instant v ^PreparedStatement ps ^long i]
    (.setTimestamp ps i (Timestamp/from v)))
andersmurphy/clj-cookbook
(ns in-any-all.core
  (:require [next.jdbc :as jdbc]
            [next.jdbc.sql :as sql]
            [clojure.string :as str]
            [next.jdbc.prepare :as p])
  (:import [java.sql PreparedStatement]))

(extend-protocol p/SettableParameter
 clojure.lang.IPersistentVector
   (set-parameter [v ^PreparedStatement s i]
     (let [conn      (.getConnection s)
           meta      (.getParameterMetaData s)
           type-name (.getParameterTypeName meta i)]
       (if-let [elem-type (when (= (first type-name) \_)
                            (apply str (rest type-name)))]
         (.setObject s i (.createArrayOf conn elem-type (to-array v)))
         (.setObject i s v)))))