Avi*_*ash 2 clojure clojure-contrib
我看下面的例子 Clojure.java.jdbc
(sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0])
Run Code Online (Sandbox Code Playgroud)
但是我如何将以下 java
代码转换为clojure
.我是新手clojure
,不知道如何通过多次vector
final int numRows = 10000;
PreparedStatement pstmt = conn
.prepareStatement("insert into new_order values (?, ?, ?)");
for (int id = 1; id <= numRows; id++) {
pstmt.setInt(1, id % 98);
pstmt.setInt(2, id % 98);
pstmt.setInt(3, id);
int count;
if ((count = pstmt.executeUpdate()) != 1) {
System.err.println("unexpected update count for a single insert " + count);
System.exit(2);
}
if ((id % 500) == 0) {
System.out.println("Completed " + id + " inserts ...");
}
}
Run Code Online (Sandbox Code Playgroud)
对于多个向量,函数是varargs:
(sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0] ["test" "test" 2 3.0])
Run Code Online (Sandbox Code Playgroud)
如果要从列表生成输入,可以使用apply:
(apply sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" (for [i (range 10)] ["test" "test" i 1.0]))
Run Code Online (Sandbox Code Playgroud)
对于该逻辑的字面再现,您不能使用varargs,因为它不会让您有机会在下一个操作之前检查每个返回值:
(let [num-rows 1000
success
(reduce
(fn [state id]
(let [values [(mod id 98)
(mod id 98)
id]
[result] (sql/do-prepared "insert into test values (?)" values)]
(if (not= result 1)
{:ok id}
(reduced {:error result}))))
(range 1 (inc num-rows)))]
(if-let [id (:ok success)]
(println "Completed" id "inserts")
(do (println "unexpected update count for a single insert" (:error success))
(System/exit 2))))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1387 次 |
最近记录: |