我在Clojure.java.jdbc
中看到以下示例
(sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0])
但是我如何将以下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 ...");
}
}
最佳答案
对于多个向量,函数是可变参数:
(sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" ["test" "test" 1 1.0] ["test" "test" 2 3.0])
如果你想从列表生成输入,你可以使用 apply:
(apply sql/db-do-prepared db "INSERT INTO fruit2 ( name, appearance, cost, grade ) VALUES ( ?, ?, ?, ? )" (for [i (range 10)] ["test" "test" i 1.0]))
对于该逻辑的字面再现,您不能使用可变参数,因为它没有给您机会在下一个操作之前检查每个返回值:
(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))))
关于Clojure db-do-prepared 调用多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20456291/