Skarab
Skarab

Reputation: 7141

How to mimic PreparedStatement to produce a valid SQL query (Sql#withBatch)

Here is my code:

// my SQL query used with PreparedStatement before
def query = "INSERT INTO TAB_A (x,y) VALUES (?,?)

Sql myDb = Sql.newInstance(...)


myDb.withBatch(10000, {stmt ->
  // I get parameters as an array
  def params = getParams();

  String rowQuery = funcThatMimicsPrepStat(query, params)

  stmt.addBatch(rowQuery);  
}

I currently looking for a way to miminc preparedstatement (funcThatMimicsPrepStat) inside withBatch, which works only with Statement. Any advice more than welcome.

Upvotes: 0

Views: 1664

Answers (1)

Benjamin Muschko
Benjamin Muschko

Reputation: 33446

Groovy 1.8.0 doesn't support it yet but it looks like one of the next minor versions will support it. The trunk source code has a couple of examples that are really helpful. Here's one example that uses a PreparedStatement:

def updateCounts = sql.withBatch(20, 'insert into TABLENAME(a, b, c) values (?, ?, ?)') { ps ->
    ps.addBatch(10, 12, 5) // varargs style
    ps.addBatch([7, 3, 98]) // list
    ps.addBatch([22, 67, 11])
    ...
}

I guess you could either snatch that piece of code or wait for a Groovy 1.8.x release.

Upvotes: 1

Related Questions