Batch insert using groovy Sql?讨论了如何批量执行多个预准备语句.但是所有语句必须具有相同的结构(作为顶级参数传入withBatch).
有没有办法批处理异构的预处理语句,如:
sql.withBatch {ps ->
ps.addBatch("insert into t1 values(:a, :b)", [a:1, b:2])
ps.addBatch("insert into t2 values(:c)", [c:3])
}
(这会引发异常,因为addBatch没有该签名.)
最佳答案 如
Oracle’s documentation中所述:
Prepared statements:
The same statement is repeated with different bind variables.Batch updates:
You can reduce the number of round-trips to the database, thereby improving application performance, by grouping multiple UPDATE, DELETE, or INSERT statements into a single batch and having the whole batch sent to the database and processed in one trip. This is especially useful in combination with a prepared statement.
如IBM’s documentation所述并摘自here:
The JDBC drivers that support JDBC 2.0 and above support batch
updates. With batch updates, instead of updating rows of a DB2(R)
table one at a time, you can direct JDBC to execute a group of updates
at the same time. Statements that can be included in the same batch of
updates are known as batchable statements.If a statement has input parameters or host expressions, you can
include that statement only in a batch that has other instances of the
same statement. This type of batch is known as a homogeneous batch. If
a statement has no input parameters, you can include that statement in
a batch only if the other statements in the batch have no input
parameters or host expressions. This type of batch is known as a
heterogeneous batch. Two statements that can be included in the same
batch are known as batch compatible.
这意味着您的请求无法执行.您可以获得的唯一优势是批量处理相同类型的语句并仅准备一次的性能改进:
执行单个SQL语句时,数据库将执行以下操作:
>准备声明
>绑定参数
>执行声明
使用批处理命令时,会发生以下情况:
>准备声明(全部收到一次传输)
>对于所有以下具有不同参数的相同语句
>绑定参数
>执行声明
由于只在节省时间后才进行准备.
但您可以对命令进行排序和拆分:
sql.withBatch(20, "insert into t1 values(:a, :b)") {
...
}
sql.withBatch(20, "insert into t2 values(:c)") {
...
}
顺便说一下,编译的是什么
sql.withBatch {ps ->
ps.addBatch("insert into t1 values(1, 2)")
ps.addBatch("insert into t2 values(3)")
}
但在这种情况下,我很好奇会发生什么:我希望JDBC驱动程序不会使用批处理.