Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the number of batches in preparedstatement?

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?

like image 418
Rakesh Juyal Avatar asked Sep 20 '10 07:09

Rakesh Juyal


1 Answers

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();
  }
}
like image 53
Arne Burmeister Avatar answered Nov 26 '22 15:11

Arne Burmeister