代码之家  ›  专栏  ›  技术社区  ›  Rakesh Juyal

如何获取PreparedStatement中的批数?

  •  9
  • Rakesh Juyal  · 技术社区  · 14 年前

    我想这一定很容易。必须有某种方法来解决这个问题。这就是我想要的:

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

    结果为:总批数:3;
    如果没有这样的方法,那怎么做呢?

    2 回复  |  直到 14 年前
        1
  •  6
  •   Arne Burmeister    14 年前

    不支持此功能。但您可以包装该语句并通过添加计数成员来重写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();
      }
    }
    
        2
  •  3
  •   nanda    14 年前

    executeBatch 将返回一个整数数组。只需计算数组的长度。

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

    推荐文章