Groovy Sql 批量执行withBatch
sql.withBatch(3) { stmt ->
stmt.addBatch "INSERT INTO Author (firstname, lastname) VALUES ('Dierk', 'Koenig')"
stmt.addBatch "INSERT INTO Author (firstname, lastname) VALUES ('Paul', 'King')"
stmt.addBatch "INSERT INTO Author (firstname, lastname) VALUES ('Guillaume', 'Laforge')"
stmt.addBatch "INSERT INTO Author (firstname, lastname) VALUES ('Hamlet', 'D''Arcy')"
stmt.addBatch "INSERT INTO Author (firstname, lastname) VALUES ('Cedric', 'Champeau')"
stmt.addBatch "INSERT INTO Author (firstname, lastname) VALUES ('Erik', 'Pragt')"
stmt.addBatch "INSERT INTO Author (firstname, lastname) VALUES ('Jon', 'Skeet')"
}
sql.withBatch 有两个参数,第二个参数为要执行操作的闭包,第一个整形的参数,表示每次的执行量。例如代码中的3,就表示调用3次addBatch方法之后,就会执行一次插入操作。
Groovy 批量执行预编译Sql
def qry = 'INSERT INTO Author (firstname, lastname) VALUES (?,?)'
sql.withBatch(3, qry) { ps ->
ps.addBatch('Dierk', 'Koenig')
ps.addBatch('Paul', 'King')
ps.addBatch('Guillaume', 'Laforge')
ps.addBatch('Hamlet', "D'Arcy")
ps.addBatch('Cedric', 'Champeau')
ps.addBatch('Erik', 'Pragt')
ps.addBatch('Jon', 'Skeet')
}
但是对于MySQL,如果使用的是InnoDB引擎,有一点要注意,InnoDB默认是的connection的autoCommit属性是打开的,在这种情况下批量插入是没有作用,因此需要把这个属性关闭。
SET autocommit=0 -- 执行sql前把自动提交关闭
commit -- 执行完sql后再提交变更数据