我想编写一个Clojure查询,以便where子句中的lnam
和fnam
参数是双引号。我需要它们双引号,因为嵌入的名称包含单引号字符,如" O' BRIEN"。
我一直在查看Clojure查询和在字符串中嵌入双引号的示例,但我找不到我想要的示例。
这在lein repl
gic-cmp.core=> (def lnam "O'BRIEN")
#'gic-cmp.core/lnam
gic-cmp.core=> (str """"lnam"""")
"O'BRIEN"
但是这不会在下面的查询中产生带引号的字符串。
(defn match-this-rec-with-last
""
[gic-id lnam fnam search-date]
(let [query (str (str "select g.* from gic_employees g where g.processed_date = '" search-date "' ")
(str "and g.gic_id = '" gic-id "' and g.last_name = ")
""""lnam""""
(str " and g.first_name = ")
(str """"fnam"""")
(str " order by g.processed_date desc "))]
(println query)
(j/query db
[query])))
答案 0 :(得分:4)
使用?对于查询参数,jdbc将正确地转义它们:
(defn match-this-rec-with-last
""
[gic-id lnam fnam search-date]
(let [query [(clojure.string/join " " ["select g.* from gic_employees g where g.processed_date = ?"
"AND g.gic_id = ? and g.last_name = ?"
"AND g.first_name = ?"
"ORDER BY g.processed_date desc"])
;; values
search-date gic-id lnam fnam]]
(println query)
(j/query db
query)))
答案 1 :(得分:3)
REPL显示str函数的返回值,并带有引号。
(str """"lnam"""")
这将返回2个空字符串,lnam和另外2个空字符串,并且都带有引号。
底层字符串是java.lang.String,在字符串中包含双引号的标准java方法是用反斜杠转义它。
user=> (str "test with \"quoted\" value")
"test with \"quoted\" value"
user=> (println (str "test with \"quoted\" value"))
test with "quoted" value