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

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

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

QueryRunner.insert介绍

[英]Executes the given INSERT SQL without any replacement parameters. The Connection is retrieved from the DataSource set in the constructor.
[中]在没有任何替换参数的情况下执行给定的INSERT SQL。Connection是从构造函数中的DataSource集合中检索的。

代码示例

代码示例来源:origin: codingapi/tx-lcn

@Override
public void tryLock(Connection connection, LockInfo lockInfo) throws SQLException {
  String lockSql = "INSERT INTO `" + txcSql.lockTableName() +
      "` (table_name, key_value, group_id, unit_id, x_lock, s_lock) values(?, ?, ?, ?, ?, ?)";
  queryRunner.insert(connection, lockSql, new ScalarHandler<Integer>(),
      lockInfo.getTableName(),
      lockInfo.getKeyValue(),
      lockInfo.getGroupId(),
      lockInfo.getUnitId(),
      lockInfo.isXLock() ? 1 : null,
      lockInfo.isXLock() ? null : 1);
}

代码示例来源:origin: testcontainers/testcontainers-java

@Test
public void testMySQLWithConnectionPoolUsingSameContainer() throws SQLException, InterruptedException {
  // Populate the database with some data in multiple threads, so that multiple connections from the pool will be used
  for (int i = 0; i < 100; i++) {
    executorService.submit(() -> {
      try {
        new QueryRunner(dataSource).insert("INSERT INTO my_counter (n) VALUES (5)",
            (ResultSetHandler<Object>) rs -> true);
      } catch (SQLException e) {
        e.printStackTrace();
      }
    });
  }
  // Complete population of the database
  executorService.shutdown();
  executorService.awaitTermination(5, TimeUnit.MINUTES);
  // compare to expected results
  int count = new QueryRunner(dataSource).query("SELECT COUNT(1) FROM my_counter", rs -> {
    rs.next();
    return rs.getInt(1);
  });
  assertEquals("Reuse of a datasource points to the same DB container", 100, count);
  int sum = new QueryRunner(dataSource).query("SELECT SUM(n) FROM my_counter", rs -> {
    rs.next();
    return rs.getInt(1);
  });
  // 100 records * 5 = 500 expected
  assertEquals("Reuse of a datasource points to the same DB container", 500, sum);
}

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

runner.insert(connection, "insert into ctl_metainfo values(?, ?, ?, ?)",
  new ScalarHandler<Long>(), mi.getId(), mi.getFqn(), mi.getAppId(), mi.getTenantId());
runner.insert(connection, "insert into ctl values(?, ?, ?, ?, ?, ?, ?)",
  new ScalarHandler<Long>(), ctl.getId(), schema.getSchems(), schema.getCreatedTime(),
  schema.getCreatedUsername(), ctl.getDefaultRecord(), schema.getVersion(), mi.getId());

代码示例来源:origin: codingapi/tx-lcn

@Override
public void writeUndoLogByGivenConnection(Connection connection, UndoLogDO undoLogDo) throws SQLException {
  log.debug("txc > write undo log. params: {}", undoLogDo);
  // 后置镜像查询 暂不记录
  txLogger.trace(undoLogDo.getGroupId(), undoLogDo.getUnitId(), "txc",
      "write undo log before. groupId: " + undoLogDo.getGroupId() +
          ", unitId: " + undoLogDo.getUnitId());
  // 写
  String undoLogSql = "INSERT INTO `"
      + txcSql.undoLogTableName()
      + "`(gmt_create, gmt_modified, group_id, unit_id, rollback_info) values(?, ?, ?, ?, ?)";
  long count = queryRunner.insert(connection, undoLogSql,
      new ScalarHandler<>(),
      undoLogDo.getGmtCreate(),
      undoLogDo.getGmtModified(),
      undoLogDo.getGroupId(),
      undoLogDo.getUnitId(),
      undoLogDo.getRollbackInfo());
  txLogger.trace(undoLogDo.getGroupId(), undoLogDo.getUnitId(), "txc", "write undo log. log id: " + count);
}

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

@Override
  public T call() throws Exception {
    return queryRunner.insert(sql, rsh, params);
  }
});

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

@Override
  public T call() throws Exception {
    return queryRunner.insert(conn, sql, rsh);
  }
});

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

@Override
  public T call() throws Exception {
    return queryRunner.insert(conn, sql, rsh, params);
  }
});

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

@Override
public T call() throws Exception {
  return queryRunner.insert(sql, rsh);
}

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

/**
 * Execute an SQL INSERT query without replacement parameters.
 * @param <T> The type of object that the handler returns
 * @param conn The connection to use to run the query.
 * @param sql The SQL to execute.
 * @param rsh The handler used to create the result object from
 * the <code>ResultSet</code> of auto-generated keys.
 * @return An object generated by the handler.
 * @throws SQLException if a database access error occurs
 * @since 1.6
 */
public <T> T insert(Connection conn, String sql, ResultSetHandler<T> rsh) throws SQLException {
  return insert(conn, false, sql, rsh, (Object[]) null);
}

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

public Long insert(String sql, Object... params) throws SQLException {
  return runner.insert(connection, sql, longKeyHandler, params);
}

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

/**
 * Execute an SQL INSERT query.
 * @param <T> The type of object that the handler returns
 * @param conn The connection to use to run the query.
 * @param sql The SQL to execute.
 * @param rsh The handler used to create the result object from
 * the <code>ResultSet</code> of auto-generated keys.
 * @param params The query replacement parameters.
 * @return An object generated by the handler.
 * @throws SQLException if a database access error occurs
 * @since 1.6
 */
public <T> T insert(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException {
  return insert(conn, false, sql, rsh, params);
}

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

public <T> T insertWithRsHandler(String sql, ResultSetHandler<T> handler, Object... params) throws SQLException {
  return runner.insert(connection, sql, handler, params);
}

代码示例来源:origin: com.github.becauseQA/becauseQA-utils

public static <T> T insert(String sql, ResultSetHandler<T> resultSetHandler, Object... params) {
  T result = null;
  synchronized (queryRunner) {
    try {
      result = queryRunner.insert(connection, sql, resultSetHandler, params);
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  return result;
}

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

/**
 * Executes the given INSERT SQL without any replacement parameters.
 * The <code>Connection</code> is retrieved from the
 * <code>DataSource</code> set in the constructor.
 * @param <T> The type of object that the handler returns
 * @param sql The SQL statement to execute.
 * @param rsh The handler used to create the result object from
 * the <code>ResultSet</code> of auto-generated keys.
 * @return An object generated by the handler.
 * @throws SQLException if a database access error occurs
 * @since 1.6
 */
public <T> T insert(String sql, ResultSetHandler<T> rsh) throws SQLException {
  return insert(this.prepareConnection(), true, sql, rsh, (Object[]) null);
}

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

/**
 * Executes the given INSERT SQL statement. 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 insert will not be saved.
 * @param <T> The type of object that the handler returns
 * @param sql The SQL statement to execute.
 * @param rsh The handler used to create the result object from
 * the <code>ResultSet</code> of auto-generated keys.
 * @param params Initializes the PreparedStatement's IN (i.e. '?')
 * @return An object generated by the handler.
 * @throws SQLException if a database access error occurs
 * @since 1.6
 */
public <T> T insert(String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException {
  return insert(this.prepareConnection(), true, sql, rsh, params);
}

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

public <T> T insert(Connection connection, String sql, Object... params) {
  try {
    return runner.insert(connection, sql, new ScalarHandler<T>(), params);
  } catch (SQLException e) {
    log.error("insert exception, sql: {}", e, sql);
    throw new DBException(e);
  }
}

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

public <T> T insert(Connection connection, String sql, Object... params) {
  try {
    return runner.insert(connection, sql, new ScalarHandler<T>(), params);
  } catch (SQLException e) {
    log.error("insert exception, sql: {}", e, sql);
    throw new DBException(e);
  }
}

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

@Test
public void testGoodInsert() throws Exception {
  results = mock(ResultSet.class);
  
  when(meta.getParameterCount()).thenReturn(2);
  when(conn.prepareStatement(any(String.class), eq(Statement.RETURN_GENERATED_KEYS))).thenReturn(stmt);
  when(stmt.getGeneratedKeys()).thenReturn(results);
  when(results.next()).thenReturn(true).thenReturn(false);
  when(results.getObject(1)).thenReturn(1L);
  Long generatedKey = runner.insert("INSERT INTO blah(col1, col2) VALUES(?,?)", new ScalarHandler<Long>(), "unit", "test");
  verify(stmt, times(1)).executeUpdate();
  verify(stmt, times(1)).close();    // make sure we closed the statement
  verify(conn, times(1)).close();    // make sure we closed the connection
  
  Assert.assertEquals(1L, generatedKey.longValue());
}

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

/**
 * Executes a given INSERT SQL prepared statement. Returns the auto-increment id of the inserted
 * row. Note: This only works when the auto-increment table column is in the first column in the
 * table!
 *
 * @param poolName The name of the connection pool to query against
 * @param sql The query to execute
 * @param params The replacement parameters
 * @return the auto-increment id of the inserted row, or null if no id is available
 */
public static Long insert(String poolName, String sql, Object[] params) throws YankSQLException {
 Long returnLong = null;
 try {
  ResultSetHandler<Long> rsh = new InsertedIDResultSetHandler();
  returnLong =
    new QueryRunner(YANK_POOL_MANAGER.getConnectionPool(poolName)).insert(sql, rsh, params);
 } catch (SQLException e) {
  handleSQLException(e, poolName, sql);
 }
 return returnLong == null ? 0 : returnLong;
}

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

@Test
public void testInsertUsesGivenQueryRunner() throws Exception {
  QueryRunner mockQueryRunner = mock(QueryRunner.class
      , org.mockito.Mockito.withSettings().verboseLogging() // debug for Continuum
      );
  runner = new AsyncQueryRunner(Executors.newSingleThreadExecutor(), mockQueryRunner);
  runner.insert("1", handler);
  runner.insert("2", handler, "param1");
  runner.insert(conn, "3", handler);
  runner.insert(conn, "4", handler, "param1");
  // give the Executor time to submit all insert statements. Otherwise the following verify statements will fail from time to time.
  TimeUnit.MILLISECONDS.sleep(50);
  verify(mockQueryRunner).insert("1", handler);
  verify(mockQueryRunner).insert("2", handler, "param1");
  verify(mockQueryRunner).insert(conn, "3", handler);
  verify(mockQueryRunner).insert(conn, "4", handler, "param1");
}

相关文章