如何获得准备好的批次数量?

时间:2010-09-20 07:48:44

标签: java batch-file prepared-statement

我认为这一定很容易。必须有一些方法。这就是我想要的: -

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

结果将是:totalbatches:3;
如果没有这样的方法那么怎么做?

2 个答案:

答案 0 :(得分:6)

不支持此功能。但是您可以通过添加计数成员来包装Statement并覆盖addBatch()。如果使用Apache Commons DBCP,则可以从DelegatingPreparedStatement继承,否则您将缺少PreparedStatement的包装器。所以我使用代理添加方法:

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();
  }
}

答案 1 :(得分:3)

executeBatch将返回一个整数数组。只需取出数组的长度。

如果您在执行批次之前需要批次,那么我想唯一的解决方法是每次调用多少个addBatch来自己计算。