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

Rak*_*yal 9 java batch-file prepared-statement

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

PreparedStatement ps = ...
ps.addBatch ( );
ps.addBatch ( );
ps.addBatch ( );
logger.info ( "totalBatches: " + ps.someMethod() ); 
ps.executeBatch ( );
Run Code Online (Sandbox Code Playgroud)

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

Arn*_*ter 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();
  }
}
Run Code Online (Sandbox Code Playgroud)


nan*_*nda 5

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

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

  • 我认为 Rakesh 想在执行之前获得批次数。否则使用 executeBatch 是可以的。 (4认同)