aboutsummaryrefslogtreecommitdiff
path: root/src/clojure/contrib/sql
diff options
context:
space:
mode:
Diffstat (limited to 'src/clojure/contrib/sql')
-rw-r--r--src/clojure/contrib/sql/sql.clj21
-rw-r--r--src/clojure/contrib/sql/test/test.clj14
2 files changed, 28 insertions, 7 deletions
diff --git a/src/clojure/contrib/sql/sql.clj b/src/clojure/contrib/sql/sql.clj
index e1becf56..313df7de 100644
--- a/src/clojure/contrib/sql/sql.clj
+++ b/src/clojure/contrib/sql/sql.clj
@@ -70,6 +70,27 @@
(do-commands con
(format "drop table %s" name)))
+(defn insert-values
+ "Inserts values into columns of a table. Columns is a seq of column
+ names (as strings) and each value is a seq of values for those
+ columns. To insert complete rows (all columns), use insert-rows"
+ [con table columns & values]
+ (let [count (count (first values))
+ template (apply str (interpose "," (replicate count "?")))
+ cols (if (seq columns)
+ (format "(%s)" (apply str (interpose "," columns)))
+ "")]
+ (apply do-prepared
+ con
+ (format "insert into %s %s values (%s)" table cols template)
+ values)))
+
+(defn insert-rows
+ "Inserts complete rows into a table. Each row is a seq of values for
+ each of the table's columns in order."
+ [con table & rows]
+ (apply insert-values con table nil rows))
+
(defmacro with-results
"Executes a query and then evaluates body repeatedly with rec bound to
each of the generated results in turn"
diff --git a/src/clojure/contrib/sql/test/test.clj b/src/clojure/contrib/sql/test/test.clj
index 90edd457..4937d96f 100644
--- a/src/clojure/contrib/sql/test/test.clj
+++ b/src/clojure/contrib/sql/test/test.clj
@@ -26,18 +26,19 @@
(try
(drop-table con "fruit")
(catch Exception e))
- (create-table con
- "fruit"
+ (create-table con "fruit"
"name varchar(32)"
"appearance varchar(32)"
"cost int"
"grade real")
- (do-prepared con
- "insert into fruit values (?, ?, ?, ?)"
+ (insert-rows con "fruit"
["Apple" "red" 59 87]
["Banana" "yellow" 29 92.2]
["Peach" "fuzzy" 139 90.0]
- ["Orange" "juicy" 89 88.6])))
+ ["Orange" "juicy" 89 88.6])
+ (insert-values con "fruit" ["name" "cost"]
+ ["Mango" 722]
+ ["Feijoa" 441])))
(defn db-read []
(with-connection con (db)
@@ -53,8 +54,7 @@
(defn db-exception []
(with-connection con (db)
- (do-prepared con
- "insert into fruit (name, appearance) values (?, ?)"
+ (insert-values con "fruit" ["name" "appearance"]
["Grape" "yummy"]
["Pear" "bruised"])
(throw (Exception. "an exception"))))