org.apache.commons.dbutils.QueryRunner.batch()方法的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(9.3k)|赞(0)|评价(0)|浏览(88)

本文整理了Java中org.apache.commons.dbutils.QueryRunner.batch方法的一些代码示例,展示了QueryRunner.batch的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。QueryRunner.batch方法的具体详情如下:
包路径:org.apache.commons.dbutils.QueryRunner
类名称:QueryRunner
方法名:batch

QueryRunner.batch介绍

[英]Execute a batch of SQL INSERT, UPDATE, or DELETE queries. The Connection is retrieved from the DataSource set in the constructor. This Connection must be in auto-commit mode or the update will not be saved.
[中]执行一批SQL插入、更新或删除查询。Connection是从构造函数中的DataSource集合中检索的。此Connection必须处于自动提交模式,否则将不会保存更新。

代码示例

代码示例来源:origin: kaaproject/kaa

/**
 * Final phase of migration -- add created ctl based schemas to database.
 *
 * @param ctlToSchemas mapping of common type to a couple of schemas
 * @throws SQLException the sql exception
 */
public void create(Map<Ctl, List<Schema>> ctlToSchemas) throws SQLException {
 List<Object[]> params = new ArrayList<>();
 int schemaCounter = 0;
 for (Ctl ctl : ctlToSchemas.keySet()) {
  for (Schema schema : ctlToSchemas.get(ctl)) {
   schemaCounter++;
   params.add(new Object[]{
     schema.getId(),
     schema.getCreatedTime(),
     schema.getCreatedUsername(),
     schema.getDescription(),
     schema.getName(),
     schema.getVersion(),
     ctl.getMetaInfo().getAppId(),
     ctl.getId()
   });
  }
 }
 runner.batch(connection, "insert into base_schems values(?, ?, ?, ?, ?, ?, ?, ?)",
   params.toArray(new Object[schemaCounter][]));
}

代码示例来源:origin: commons-dbutils/commons-dbutils

@Override
public int[] call() throws Exception {
  return queryRunner.batch(sql, params);
}

代码示例来源:origin: commons-dbutils/commons-dbutils

@Override
public int[] call() throws Exception {
  return queryRunner.batch(conn, sql, params);
}

代码示例来源:origin: commons-dbutils/commons-dbutils

/**
 * Execute a batch of SQL INSERT, UPDATE, or DELETE queries.
 *
 * @param conn The Connection to use to run the query.  The caller is
 * responsible for closing this Connection.
 * @param sql The SQL to execute.
 * @param params An array of query replacement parameters.  Each row in
 * this array is one set of batch replacement values.
 * @return The number of rows updated per statement.
 * @throws SQLException if a database access error occurs
 * @since DbUtils 1.1
 */
public int[] batch(Connection conn, String sql, Object[][] params) throws SQLException {
  return this.batch(conn, false, sql, params);
}

代码示例来源:origin: i38/kaixin

public int[] updateBatch(String sql, Object[][] params) throws SQLException {
  return runner.batch(connection, sql, params);
}

代码示例来源:origin: coffeewar/enode-master

@Override
public int update(QueryRunner queryRunner, Connection connection) throws SQLException {
  try {
    queryRunner.batch(connection, sql, params);
    return 0;
  } catch (SQLException ex) {
    if (ex.getErrorCode() == 1062 && ignoreDuplicate) { //主键冲突,忽略即可;出现这种情况,是因为同一个消息的重复处理
      insertOneByOne(queryRunner, connection);
      return 0;
    }
    throw ex;
  }
}

代码示例来源:origin: commons-dbutils/commons-dbutils

/**
 * Execute a batch of SQL INSERT, UPDATE, or DELETE queries.  The
 * <code>Connection</code> is retrieved from the <code>DataSource</code>
 * set in the constructor.  This <code>Connection</code> must be in
 * auto-commit mode or the update will not be saved.
 *
 * @param sql The SQL to execute.
 * @param params An array of query replacement parameters.  Each row in
 * this array is one set of batch replacement values.
 * @return The number of rows updated per statement.
 * @throws SQLException if a database access error occurs
 * @since DbUtils 1.1
 */
public int[] batch(String sql, Object[][] params) throws SQLException {
  Connection conn = this.prepareConnection();
  return this.batch(conn, true, sql, params);
}

代码示例来源:origin: stackoverflow.com

/**
 * Insert batch of rows from model list into the Database.
 * 
 * @param modelsList List of model objects representing the Database table.
 * @return int Array of inserted rows.
 * @throws SQLException
 */
public <T> int[] insertWithListOfModels(List<T> modelsList) throws SQLException{
  ModelToSqlConverter modelConverter = new ModelToSqlConverter(modelsList);
  QueryRunner qryRunner = new QueryRunner();
  int[] inserts = null;
  System.out.println("INSERT INTO " + modelsList.get(0).getClass().getSimpleName().toUpperCase() + " " + modelConverter.getSqlString());
  System.out.println(Arrays.deepToString(modelConverter.getMultiValueParams()));
  inserts = qryRunner.batch(connection,
      "INSERT INTO " + modelsList.get(0).getClass().getSimpleName().toUpperCase() + " " + modelConverter.getSqlString(),
      modelConverter.getMultiValueParams());
  return inserts;
}

代码示例来源:origin: com.github.biezhi/unique-support-orm

/**
 * 批量更新
 */
public static int[] updateBatch(String sql, List<Object[]> list) {
  int[] result = {};
  try {
    Object[] param = list.toArray();
    Object[][] params = new Object[param.length][];
    logger.debug("Sql:" + sql);
    logger.debug("Parameters:" + Arrays.toString(list.toArray()));
    result = getQueryRunner().batch(getConn(), sql, params);
  } catch (SQLException e) {
    throw new UpdateException(e);
  }
  return result;
}

代码示例来源:origin: commons-dbutils/commons-dbutils

private void callGoodBatch(Connection conn, Object[][] params) throws Exception {
  when(meta.getParameterCount()).thenReturn(2);
  runner.batch(conn, "select * from blah where ? = ?", params);
  verify(stmt, times(2)).addBatch();
  verify(stmt, times(1)).executeBatch();
  verify(stmt, times(1)).close();    // make sure we closed the statement
  verify(conn, times(0)).close();    // make sure we do not close the connection, since QueryRunner.batch(Connection, String, Object[][]) does not close connections
}

代码示例来源:origin: commons-dbutils/commons-dbutils

private void callGoodBatch(Object[][] params) throws Exception {
  when(meta.getParameterCount()).thenReturn(2);
  runner.batch("select * from blah where ? = ?", params);
  verify(stmt, times(2)).addBatch();
  verify(stmt, times(1)).executeBatch();
  verify(stmt, times(1)).close();    // make sure we closed the statement
  verify(conn, times(1)).close();    // make sure we closed the connection
}

代码示例来源:origin: hypercube1024/firefly

@Override
public CompletableFuture<int[]> executeBatch(String sql, Object[][] params) {
  return jdbcHelper.async(connection, (conn, helper) -> {
    try {
      return helper.getRunner().batch(connection, sql, params);
    } catch (SQLException e) {
      throw new DBException(e);
    }
  });
}

代码示例来源:origin: com.fireflysource/firefly-db

@Override
public CompletableFuture<int[]> executeBatch(String sql, Object[][] params) {
  return jdbcHelper.async(connection, (conn, helper) -> {
    try {
      return helper.getRunner().batch(connection, sql, params);
    } catch (SQLException e) {
      throw new DBException(e);
    }
  });
}

代码示例来源:origin: XavientInformationSystems/Data-Ingestion-Platform

@Override
protected void finishBatch() {
  List<Tuple> tuples = new ArrayList<Tuple>();
  queue.drainTo(tuples);
  try {
    if (CollectionUtils.isNotEmpty(tuples)) {
      int t = 0;
      List<String> fields = getFileds(tuples.get(0));
      Object[][] data = new Object[tuples.size()][];
      for (Tuple tuple : tuples) {
        Object[] value = new Object[] { tuple.getValueByField(fields.get(0)),
            tuple.getValueByField(fields.get(1)), tuple.getValueByField(fields.get(1)) };
        data[t] = value;
        t++;
      }
      queryRunner.batch(buildQuery(tuples.get(0).getStringByField("tableName"), fields), data);
    }
  } catch (Exception e) {
    LOG.error("Exception occurred while executing query", e);
  }
}

代码示例来源:origin: commons-dbutils/commons-dbutils

private void callBatchWithException(String sql, Object[][] params) throws Exception {
  boolean caught = false;
  try {
    runner.batch(sql, params);
    verify(stmt, times(2)).addBatch();
    verify(stmt, times(1)).executeBatch();
    verify(stmt, times(1)).close();    // make sure the statement is closed
    verify(conn, times(1)).close();    // make sure the connection is closed
  } catch(SQLException e) {
    caught = true;
  }
  if(!caught) {
    fail("Exception never thrown, but expected");
  }
}

代码示例来源:origin: commons-dbutils/commons-dbutils

@Test(expected=SQLException.class)
public void testNullConnectionBatch() throws Exception {
  String[][] params = new String[][] { { "unit", "unit" }, { "test", "test" } };
  when(meta.getParameterCount()).thenReturn(2);
  when(dataSource.getConnection()).thenReturn(null);
  runner.batch("select * from blah where ? = ?", params);
}

代码示例来源:origin: commons-dbutils/commons-dbutils

@Test(expected=SQLException.class)
public void testNullSqlBatch() throws Exception {
  String[][] params = new String[][] { { "unit", "unit" }, { "test", "test" } };
  when(meta.getParameterCount()).thenReturn(2);
  runner.batch(null, params);
}

代码示例来源:origin: commons-dbutils/commons-dbutils

@Test(expected=SQLException.class)
public void testNullParamsArgBatch() throws Exception {
  when(meta.getParameterCount()).thenReturn(2);
  runner.batch("select * from blah where ? = ?", null);
}

代码示例来源:origin: org.knowm/yank

/**
 * Batch executes the given INSERT, UPDATE, DELETE, REPLACE or UPSERT SQL statement
 *
 * @param poolName The name of the connection pool to query against
 * @param sql The SQL statement
 * @param params An array of query replacement parameters. Each row in this array is one set of
 *     batch replacement values
 * @return The number of rows affected or each individual execution
 */
public static int[] executeBatch(String poolName, String sql, Object[][] params)
  throws YankSQLException {
 int[] returnIntArray = null;
 try {
  returnIntArray =
    new QueryRunner(YANK_POOL_MANAGER.getConnectionPool(poolName)).batch(sql, params);
 } catch (SQLException e) {
  handleSQLException(e, poolName, sql);
 }
 return returnIntArray;
}

代码示例来源:origin: knowm/Yank

/**
 * Batch executes the given INSERT, UPDATE, DELETE, REPLACE or UPSERT SQL statement
 *
 * @param poolName The name of the connection pool to query against
 * @param sql The SQL statement
 * @param params An array of query replacement parameters. Each row in this array is one set of
 *     batch replacement values
 * @return The number of rows affected or each individual execution
 */
public static int[] executeBatch(String poolName, String sql, Object[][] params)
  throws YankSQLException {
 int[] returnIntArray = null;
 try {
  returnIntArray =
    new QueryRunner(YANK_POOL_MANAGER.getConnectionPool(poolName)).batch(sql, params);
 } catch (SQLException e) {
  handleSQLException(e, poolName, sql);
 }
 return returnIntArray;
}

相关文章