Batch insert using groovy Sql?

Jared picture Jared · May 17, 2010 · Viewed 16.8k times · Source

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 http://jira.codehaus.org/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?

Answer

topchef picture topchef · Sep 1, 2011

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