JDBC的批量操作Batch

 

语句队列,用链表存储是为了保证先到的语句能先执行

  * 加到当前批次
  *
  * @param conn
  *            数据库连接
  * @param sql
  *            sql语句
  * @param callback
  *            绑定变量回调接口
  * @throws SinoException
  */
 public void addToBatch(Connection conn, String sql, Callback callback) throws SinoException {
  PreparedStatement ps = null;
  try {
   if (currentSql != null && sql.hashCode() == currentSql.hashCode()
     && sql.length() == currentSql.length()) {

    ps = (PreparedStatement) statementList.getLast();
   } else {
    conn = SysUtility.check(conn);
    ps = SQLExecUtils.getProxy(conn.prepareStatement(sql));
    statementList.addLast(ps);
    currentSql = sql;
   }
   callback.doIn(ps);
   ps.addBatch();
  } catch (SQLException e) {
   throw SinoException.getSinoException(e);
  }
  LogUtil.printLog("add to batch :" + sql, LogUtil.DEBUG);
  size++;
 }

 

public boolean executeBatch() throws SinoException {
  if (isEmpty()) {
   return true;
  }

  long start = System.currentTimeMillis();

  try {
   for (int i = 0; i < statementList.size(); i++) {
    PreparedStatement ps = (PreparedStatement)statementList.get(i);
    ps.executeBatch();
    isNullUpdated(ps.getUpdateCount());
   }
  } catch (SQLException e) {
   throw SinoException.getSinoException(e);
  } finally {
   clear();
  }
  LogUtil.printLog("executeBatch cost " + (System.currentTimeMillis() - start) + " ms!",
    LogUtil.DEBUG);
  return isNullUpdated();
 }

 

阅读更多
个人分类: JAVA JDBC
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭