If UPDATE, INSERT or DELETE, return BatchPreparedStatement,
otherwise return null.
162023
private PreparedStatement prepareBatchStatement(String sql)
    {
        String sqlCmd = sql.substring(0, 7);

        if (sqlCmd.equals("UPDATE ") || sqlCmd.equals("DELETE ") || (_useBatchInserts && sqlCmd.equals("INSERT ")))
        {
            PreparedStatement stmt = (PreparedStatement) _statements.get(sql);
            if (stmt == null)
            {
                // [olegnitz] for JDK 1.2 we need to list both PreparedStatement and Statement
                // interfaces, otherwise proxy.jar works incorrectly
                stmt = (PreparedStatement) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{
                        PreparedStatement.class, Statement.class, BatchPreparedStatement.class},
                        new PreparedStatementInvocationHandler(this, sql, m_jcd));
                _statements.put(sql, stmt);
            }
            return stmt;
        }
        else
        {
            return null;
        }
    }
1132959
public static int update(PreparedStatement stmt) throws SQLException {
		int rows = stmt.executeUpdate();
		stmt.close();
		return rows;
	}
957205
public int update(List<ENTITY> entities) {

        if (entities == null || entities.size() == 0) {
            recordLog(" param entity is null!");
            return 0;
        }

        final List<Query> queries = queryGenerator.getUpdateQuery(entities);
        String sql = queries.get(0).getSql();
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

            public void setValues(PreparedStatement stmt, int index) throws SQLException {
                int i = 1;
                List<Object> params = queries.get(index).getParams();
                for (Object o : params) {
                    stmt.setObject(i++, o);
                }
            }

            public int getBatchSize() {
                return queries.size();
            }
        });

        return entities.size();
    }
347456
public PreparedStatement getPreparedStatement(ClassDescriptor cds, String sql,
                                                  boolean scrollable, int explicitFetchSizeHint, boolean callableStmt)
            throws PersistenceBrokerException
    {
        try
        {
            return cds.getStatementsForClass(m_conMan).getPreparedStmt(m_conMan.getConnection(), sql, scrollable, explicitFetchSizeHint, callableStmt);
        }
        catch (LookupException e)
        {
            throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e);
        }
    }
137466
private PrepareResult executeBatchStandard(int estimatedParameterCount) throws SQLException {
    int totalExecutionNumber = getTotalExecutionNumber();
    SQLException exception = null;
    BulkStatus status = new BulkStatus();

    ComStmtPrepare comStmtPrepare = null;
    FutureTask<AsyncMultiReadResult> futureReadTask = null;

    int requestNumberByBulk;
    int paramCount = estimatedParameterCount;
    try {
      do {
        status.sendEnded = false;
        status.sendSubCmdCounter = 0;
        requestNumberByBulk = Math.min(totalExecutionNumber - status.sendCmdCounter,
            protocol.getOptions().useBatchMultiSendNumber);
        protocol.changeSocketTcpNoDelay(false); //enable NAGLE algorithm temporary.

        //add prepare sub-command
        if (readPrepareStmtResult && prepareResult == null) {

          comStmtPrepare = new ComStmtPrepare(protocol, sql);
          comStmtPrepare.send(writer);

          //read prepare result
          prepareResult = comStmtPrepare.read(protocol.getReader(), protocol.isEofDeprecated());
          statementId = ((ServerPrepareResult) prepareResult).getStatementId();
          paramCount = getParamCount();
        }

        boolean useCurrentThread = false;

        for (; status.sendSubCmdCounter < requestNumberByBulk; ) {
          sendCmd(writer, results, parametersList, queries, paramCount, status, prepareResult);
          status.sendSubCmdCounter++;
          status.sendCmdCounter++;
          if (useCurrentThread) {
            try {
              protocol.getResult(results);
            } catch (SQLException qex) {
              if (((readPrepareStmtResult && prepareResult == null) || !protocol
                  .getOptions().continueBatchOnError)) {
                throw qex;
              } else {
                exception = qex;
              }
            }
          } else if (futureReadTask == null) {
            try {
              futureReadTask = new FutureTask<>(new AsyncMultiRead(comStmtPrepare, status,
                  protocol, false, this, paramCount,
                  results, parametersList, queries, prepareResult));
              AbstractQueryProtocol.readScheduler.execute(futureReadTask);
            } catch (RejectedExecutionException r) {
              useCurrentThread = true;
              try {
                protocol.getResult(results);
              } catch (SQLException qex) {
                if (((readPrepareStmtResult && prepareResult == null) || !protocol
                    .getOptions().continueBatchOnError)) {
                  throw qex;
                } else {
                  exception = qex;
                }
              }
            }
          }
        }

        status.sendEnded = true;
        if (!useCurrentThread) {
          protocol.changeSocketTcpNoDelay(protocol.getOptions().tcpNoDelay);
          try {
            AsyncMultiReadResult asyncMultiReadResult = futureReadTask.get();

            if (binaryProtocol && prepareResult == null
                && asyncMultiReadResult.getPrepareResult() != null) {
              prepareResult = asyncMultiReadResult.getPrepareResult();
              statementId = ((ServerPrepareResult) prepareResult).getStatementId();
              paramCount = prepareResult.getParamCount();
            }

            if (asyncMultiReadResult.getException() != null) {
              if (((readPrepareStmtResult && prepareResult == null) || !protocol
                  .getOptions().continueBatchOnError)) {
                throw asyncMultiReadResult.getException();
              } else {
                exception = asyncMultiReadResult.getException();
              }
            }
          } catch (ExecutionException executionException) {
            if (executionException.getCause() == null) {
              throw new SQLException("Error reading results " + executionException.getMessage());
            }
            throw new SQLException(
                "Error reading results " + executionException.getCause().getMessage());
          } catch (InterruptedException interruptedException) {
            protocol.setActiveFutureTask(futureReadTask);
            Thread.currentThread().interrupt();
            throw new SQLException("Interrupted awaiting response ",
                INTERRUPTED_EXCEPTION.getSqlState(), interruptedException);
          } finally {
            //bulk can prepare, and so if prepare cache is enable, can replace an already cached prepareStatement
            //this permit to release those old prepared statement without conflict.
            protocol.forceReleaseWaitingPrepareStatement();
          }
        }

        if (protocol.isInterrupted()) {
          //interrupted during read, must throw an exception manually
          futureReadTask.cancel(true);
          throw new SQLTimeoutException("Timeout during batch execution");
        }
        futureReadTask = null;

      } while (status.sendCmdCounter < totalExecutionNumber);

      if (exception != null) {
        throw exception;
      }

      return prepareResult;

    } catch (IOException e) {
      status.sendEnded = true;
      status.sendCmdCounter = 0; //to ensure read doesn't hang
      throw protocol.handleIoException(e);
    }

  }
839869
@Override
	public synchronized void update(long paramId, int used, String flags,
			String values) throws DatabaseException {
    	SqlPreparedStatementWrapper psUpdate = null;
        try {
        	psUpdate = DbSQL.getSingleton().getPreparedStatement("param.ps.update");
			psUpdate.getPs().setInt(1, used);
			psUpdate.getPs().setString(2, flags);
			psUpdate.getPs().setString(3, values);
			psUpdate.getPs().setLong(4, paramId);
			psUpdate.getPs().executeUpdate();
		} catch (SQLException e) {
			throw new DatabaseException(e);
		} finally {
			DbSQL.getSingleton().releasePreparedStatement(psUpdate);
		}
    }
197943
@Override
    public int executeBatch()
    {
        Map<String, List<Row>> batchData = new HashMap<String, List<Row>>();
        try
        {
            for (Node node : nodes)
            {
                if (node.isDirty())
                {
                    Row action = null;
                    node.handlePreEvent();
                    Object rowKey = node.getEntityId();
                    Object entity = node.getData();
                    EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, node.getDataClass());
                    String tableName = HBaseUtils.getHTableName(m.getSchema(), m.getTableName());
                    if (node.isInState(RemovedState.class))
                    {
                        action = handler.prepareDelete(rowKey);
                    }
                    else
                    {
                        HBaseRow hbaseRow = ((HBaseDataHandler) handler).createHbaseRow(m, entity, rowKey, null);
                        action = handler.preparePut(hbaseRow);
                    }
                    node.handlePostEvent();
                    if (!batchData.containsKey(tableName))
                    {
                        batchData.put(tableName, new ArrayList<Row>());
                    }
                    batchData.get(tableName).add(action);
                }
            }

            if (!batchData.isEmpty())
            {
                ((HBaseDataHandler) handler).batchProcess(batchData);
            }
            return batchData.size();
        }
        catch (IOException ioex)
        {
            log.error("Error while executing batch insert/update, Caused by: .", ioex);
            throw new KunderaException(ioex);
        }

    }
832324
@Override
    public int executeUpdate() throws SQLException
    {
        checkClosed();
        if (!this.Query.isOfType(VoltSQL.TYPE_EXEC,VoltSQL.TYPE_UPDATE)) {
            throw SQLError.get(SQLError.ILLEGAL_STATEMENT, this.Query.toSqlString());
        }
        int result = this.executeUpdate(this.Query.getExecutableQuery(this.parameters));
        this.parameters = this.Query.getParameterArray();
        return result;
    }
1289482
private void insert(BatchExecutor batchExecutor, MappingConfig config, SingleDml dml) throws SQLException {
        Map<String, Object> data = dml.getData();
        if (data == null || data.isEmpty()) {
            return;
        }

        DbMapping dbMapping = config.getDbMapping();

        Map<String, String> columnsMap = SyncUtil.getColumnsMap(dbMapping, data);

        StringBuilder insertSql = new StringBuilder();
        insertSql.append("INSERT INTO ").append(SyncUtil.getDbTableName(dbMapping)).append(" (");

        columnsMap.forEach((targetColumnName, srcColumnName) -> insertSql.append(targetColumnName).append(","));
        int len = insertSql.length();
        insertSql.delete(len - 1, len).append(") VALUES (");
        int mapLen = columnsMap.size();
        for (int i = 0; i < mapLen; i++) {
            insertSql.append("?,");
        }
        len = insertSql.length();
        insertSql.delete(len - 1, len).append(")");

        Map<String, Integer> ctype = getTargetColumnType(batchExecutor.getConn(), config);

        List<Map<String, ?>> values = new ArrayList<>();
        for (Map.Entry<String, String> entry : columnsMap.entrySet()) {
            String targetColumnName = entry.getKey();
            String srcColumnName = entry.getValue();
            if (srcColumnName == null) {
                srcColumnName = Util.cleanColumn(targetColumnName);
            }

            Integer type = ctype.get(Util.cleanColumn(targetColumnName).toLowerCase());
            if (type == null) {
                throw new RuntimeException("Target column: " + targetColumnName + " not matched");
            }
            Object value = data.get(srcColumnName);
            BatchExecutor.setValue(values, type, value);
        }

        try {
            batchExecutor.execute(insertSql.toString(), values);
        } catch (SQLException e) {
            if (skipDupException
                && (e.getMessage().contains("Duplicate entry") || e.getMessage().startsWith("ORA-00001: 违反唯一约束条件"))) {
                // ignore
                // TODO 增加更多关系数据库的主键冲突的错误码
            } else {
                throw e;
            }
        }
        if (logger.isTraceEnabled()) {
            logger.trace("Insert into target table, sql: {}", insertSql);
        }

    }
213249
int update(Config config, Connection conn, String sql, Object... paras) throws SQLException {
		PreparedStatement pst = conn.prepareStatement(sql);
		config.dialect.fillStatement(pst, paras);
		int result = pst.executeUpdate();
		DbKit.close(pst);
		return result;
	}
328316
public ResultSet executeWithKeys() {
        context = startContext(connection(), metadata, entity);
        try {
            PreparedStatement stmt = null;
            if (batches.isEmpty()) {
                stmt = createStatement(true);
                listeners.notifyInsert(entity, metadata, columns, values, subQuery);

                listeners.preExecute(context);
                stmt.executeUpdate();
                listeners.executed(context);
            } else if (batchToBulk) {
                stmt = createStatement(true);
                listeners.notifyInserts(entity, metadata, batches);

                listeners.preExecute(context);
                stmt.executeUpdate();
                listeners.executed(context);
            } else {
                Collection<PreparedStatement> stmts = createStatements(true);
                if (stmts != null && stmts.size() > 1) {
                    throw new IllegalStateException("executeWithKeys called with batch statement and multiple SQL strings");
                }
                stmt = stmts.iterator().next();
                listeners.notifyInserts(entity, metadata, batches);

                listeners.preExecute(context);
                stmt.executeBatch();
                listeners.executed(context);
            }

            final Statement stmt2 = stmt;
            ResultSet rs = stmt.getGeneratedKeys();
            return new ResultSetAdapter(rs) {
                @Override
                public void close() throws SQLException {
                    try {
                        super.close();
                    } finally {
                        stmt2.close();
                        reset();
                        endContext(context);
                    }
                }
            };
        } catch (SQLException e) {
            onException(context, e);
            reset();
            endContext(context);
            throw configuration.translate(queryString, constants, e);
        }
    }
788708
protected void initializeBatch(String databaseName, String table)
      throws SQLException {
    this.insertStmtPrefix = createInsertStatementStr(databaseName, table);
    this.insertPstmtForFixedBatch =
        this.conn.prepareStatement(createPrepareStatementStr(this.batchSize));
    LOG.info(String.format("Initialized for %s insert " + this, (this.batchSize > 1) ? "batch" : ""));
  }
1362538
public int update(DatabaseConnection databaseConnection, PreparedUpdate<T> preparedUpdate) throws SQLException {
		CompiledStatement compiledStatement = preparedUpdate.compile(databaseConnection, StatementType.UPDATE);
		try {
			int result = compiledStatement.runUpdate();
			if (dao != null && !localIsInBatchMode.get()) {
				dao.notifyChanges();
			}
			return result;
		} finally {
			IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
		}
	}
280657
@Override
    public PoolablePreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
        return new PoolablePreparedStatement(internalConn.prepareStatement(sql, columnIndexes), this, null);
    }
1250141
protected int doUpdate(JdbcTemplate jdbcTemplate, TaskRequest req, TaskResponse res) {
        //Setup the update parameters and setter
        final List<Phrase> parametersInUse = update_parameters != null ? update_parameters : parameters;
        final PreparedStatementSetter preparedStatementSetter = new PhraseParameterPreparedStatementSetter(parametersInUse, req, res);
        
        //Get the update sql and execute the update.
        final String fUpdateSql = (String) update_sql.evaluate(req, res);
        return jdbcTemplate.update(fUpdateSql, preparedStatementSetter);
    }
774637
private void getFKStatement(StringBuffer a) {

        if (!getName().isReservedName()) {
            a.append(Tokens.T_CONSTRAINT).append(' ');
            a.append(getName().statementName);
            a.append(' ');
        }

        a.append(Tokens.T_FOREIGN).append(' ').append(Tokens.T_KEY);

        int[] col = getRefColumns();

        getColumnList(getRef(), col, col.length, a);
        a.append(' ').append(Tokens.T_REFERENCES).append(' ');
        a.append(getMain().getName().getSchemaQualifiedStatementName());

        col = getMainColumns();

        getColumnList(getMain(), col, col.length, a);

        if (getDeleteAction() != Constraint.NO_ACTION) {
            a.append(' ').append(Tokens.T_ON).append(' ').append(
                Tokens.T_DELETE).append(' ');
            a.append(getDeleteActionString());
        }

        if (getUpdateAction() != Constraint.NO_ACTION) {
            a.append(' ').append(Tokens.T_ON).append(' ').append(
                Tokens.T_UPDATE).append(' ');
            a.append(getUpdateActionString());
        }
    }
763921
public void setNullForStatement(PreparedStatement ps, int index, int sqlType) throws SQLException
    {
        ps.setNull(index, sqlType);
    }