DB access companion format function

Artificial Intelligence Technology   Semantic Web Technology   Search Technology     DataBase Technology   Ontology Technology   Digital Transformation Technology   User Interface and DataVisualization   Workflow & Services.  Programming  Clojure    Database Technologies

When accessing a database in Clojure, flexible database access can be achieved by using a part of the query statement such as SQL as a variable. The “format function” is a beautiful way to achieve this. The basic usage is as follows.

user=> (format "Hello there, %s" "bob")
"Hello there, bob"

‘%s’ represents a string variable, and for numbers, use %d or %o,%x. If you want to access a SQL DB, for example, use

(defn db-query [q1 q2]
(jdbc/query db-spec 
(format "select %s from member where id = %s" q1 q2))

can be converted to a function that treats the output as a variable in q1 and the id as a variable in q2.This is also useful for outputting the result by assigning it in text

(defn output-text [x] (format "今回の結果は%sです。" x)

In the case of numeric output, it can also be transformed by specifying variables as shown below.

user=> (format "%5d" 3)
"    3"

user=> (format "Pad with leading zeros %07d" 5432)
"Pad with leading zeros 0005432"

user=> (format "Left justified :%-7d:" 5432)
"Left justified :5432   :"

user=> (format "Locale-specific group separators %,12d" 1234567)
"Locale-specific group separators    1,234,567"

user=> (format "decimal %d  octal %o  hex %x  upper-case hex %X" 63 63 63 63)
"decimal 63  octal 77  hex 3f  upper-case hex 3F"

user=> (format "%2$d %1$s" "Positional arguments" 23)
"23 Positional arguments"

It is a simple but useful function to remember.

コメント

タイトルとURLをコピーしました