views:

38

answers:

2

I think this must be easy. There must be some method for this. This is what i want:-

PreparedStatement ps = ...
ps.addBatch ( );
ps.addBatch ( );
ps.addBatch ( );
logger.info ( "totalBatches: " + ps.someMethod() ); 
ps.executeBatch ( );

result will be: totalbatches: 3;
If there is no such method then how to do this?

+1  A: 

executeBatch will return an array of integers. Just take the length of the array.

If you need the number of batches before it is executed, then I guess the only workaround is to count it yourself everytime how many addBatch you've called.

nanda
I think Rakesh would like to get number of batches before the execution. Otherwise using executeBatch is OK.
rics
@rics: tht's right
Rakesh Juyal
+4  A: 

This functionality is not supported. But you can wrap the Statement and override addBatch() by adding a counting member. If using Apache Commons DBCP, you can inherit from DelegatingPreparedStatement, else you have a lack of a wrapper for PreparedStatement. So I used a proxy to add the method:

public class BatchCountingStatementHandler implements InvocationHandler {

  public static BatchCountingStatement countBatches(PreparedStatement delegate) {
    return Proxy.newProxyInstance(delegate.getClassLoader(), new Class[] {BatchCountingStatement.class}, new BatchCountingStatementHandler(delegate));
  }

  private final PreparedStatement delegate;
  private int count = 0;

  private BatchCountingStatementHandler(PreparedStatement delegate) {
    this.delegate = delegate;
  }

  public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable {
    if ("getBatchCount".equals(method.getName())) {
      return count;
    }
    try {
      return method.invoke(delegate, args);
    } finally {
      if ("addBatch".equals(method.getName())) {
        ++count;
      }
    }
  }

  public static interface BatchCountingStatement extends PreparedStatement {
    public int getBatchCount();
  }
}
Arne Burmeister