Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch insert using groovy Sql?

How can you do a batch insert using groovy Sql while simulating prepared statements? All the examples I've found are similar to the following and don't use prepared statements.

withBatch  { stmt ->
stmt.addBatch("insert into table (field1,field2) values('value1','value2')")
stmt.addBatch("insert into table (field1,field2) values('value3','value4')")
}

According to this link https://issues.apache.org/jira/browse/GROOVY-3504 there is no way to use prepared statements directly from within batch. What is the best way to simulate this so I can avoid having to write my own code to avoid sql injection?

like image 734
Jared Avatar asked May 17 '10 12:05

Jared


2 Answers

Groovy 1.8.1 introduced support for prepared statements with batching. Simple example:

sql.withBatch(20, """update some_table 
                        set some_column = :newvalue 
                      where id = :key """) { ps ->                 
          mymap.each { k,v ->
              ps.addBatch(key:k, newvalue:v)
          }
}

Also see my post on the topic: http://novyden.blogspot.com/2011/09/groovy-batch-prepared-statement-nice.html

like image 187
topchef Avatar answered Sep 27 '22 21:09

topchef


It's supported from version 1.8.1. You can read the Groovy 1.8.1 release notes for details. Pls check the API Document for help.

like image 25
Weirong Xu Avatar answered Sep 27 '22 22:09

Weirong Xu