Execute SQL stmt.

@param _sqlProvider the sql provider
@param _complStmt the compl stmt
@return true, if successful
@throws EFapsException the e faps exception
518353
@SuppressWarnings("unchecked")
    protected boolean executeSQLStmt(final ISelectionProvider _sqlProvider, final String _complStmt)
        throws EFapsException
    {
        SQLRunner.LOG.debug("SQL-Statement: {}", _complStmt);

        boolean ret = false;
        List<Object[]> rows = new ArrayList<>();

        boolean cached = false;
        if (runnable.has(StmtFlag.REQCACHED)) {
            final QueryKey querykey = QueryKey.get(Context.getThreadContext().getRequestId(), _complStmt);
            final Cache<QueryKey, Object> cache = QueryCache.getSqlCache();
            if (cache.containsKey(querykey)) {
                final Object object = cache.get(querykey);
                if (object instanceof List) {
                    rows = (List<Object[]>) object;
                }
                cached = true;
            }
        }
        if (!cached) {
            ConnectionResource con = null;
            try {
                con = Context.getThreadContext().getConnectionResource();
                final Statement stmt = con.createStatement();
                final ResultSet rs = stmt.executeQuery(_complStmt);
                final ArrayListHandler handler = new ArrayListHandler(Context.getDbType().getRowProcessor());
                rows = handler.handle(rs);
                rs.close();
                stmt.close();
            } catch (final SQLException e) {
                throw new EFapsException(SQLRunner.class, "executeOneCompleteStmt", e);
            }
            if (runnable.has(StmtFlag.REQCACHED)) {
                final ICacheDefinition cacheDefinition = new ICacheDefinition() {

                    @Override
                    public long getLifespan()
                    {
                        return 5;
                    }

                    @Override
                    public TimeUnit getLifespanUnit()
                    {
                        return TimeUnit.MINUTES;
                    }
                };
                QueryCache.put(cacheDefinition, QueryKey.get(Context.getThreadContext().getRequestId(), _complStmt), rows);
            }
        }
        for (final Object[] row : rows) {
            for (final Select select : _sqlProvider.getSelection().getAllSelects()) {
                select.addObject(row);
            }
            ret = true;
        }
        return ret;
    }
1185626
public boolean execute(final OneSelect _onesel)
        throws EFapsException
    {
        this.hasResult = executeOneCompleteStmt(createSQLStatement(_onesel), getAllSelects());
        if (this.hasResult) {
            for (final OneSelect onesel :  getAllSelects()) {
                if (onesel.getFromSelect() != null && !onesel.getFromSelect().equals(this)) {
                    onesel.getFromSelect().execute(onesel);
                }
            }
        }
        return this.hasResult;
    }
994644
@Override
  public void executeQuery(boolean mustExecuteOnMaster, Results results, final String sql)
      throws SQLException {

    cmdPrologue();
    try {

      writer.startPacket(0);
      writer.write(COM_QUERY);
      writer.write(sql);
      writer.flush();
      getResult(results);

    } catch (SQLException sqlException) {
      if ("70100".equals(sqlException.getSQLState()) && 1927 == sqlException.getErrorCode()) {
        throw handleIoException(sqlException);
      }
      throw logQuery.exceptionWithQuery(sql, sqlException, explicitClosed);
    } catch (IOException e) {
      throw handleIoException(e);
    }

  }
866652
@Override
  public void executePreparedQuery(boolean mustExecuteOnMaster,
      ServerPrepareResult serverPrepareResult, Results results,
      ParameterHolder[] parameters)
      throws SQLException {

    cmdPrologue();

    try {

      int parameterCount = serverPrepareResult.getParameters().length;

      //send binary data in a separate stream
      for (int i = 0; i < parameterCount; i++) {
        if (parameters[i].isLongData()) {
          writer.startPacket(0);
          writer.write(COM_STMT_SEND_LONG_DATA);
          writer.writeInt(serverPrepareResult.getStatementId());
          writer.writeShort((short) i);
          parameters[i].writeBinary(writer);
          writer.flush();
        }
      }

      //send execute query
      ComStmtExecute.send(writer, serverPrepareResult.getStatementId(), parameters,
              parameterCount, serverPrepareResult.getParameterTypeHeader(), CURSOR_TYPE_NO_CURSOR);
      getResult(results);

    } catch (SQLException qex) {
      throw logQuery.exceptionWithQuery(parameters, qex, serverPrepareResult);
    } catch (IOException e) {
      throw handleIoException(e);
    }
  }
1328455
private int bindStatement(PreparedStatement stmt, int index, BetweenCriteria crit, ClassDescriptor cld) throws SQLException
    {
        index = bindStatementValue(stmt, index, crit.getAttribute(), crit.getValue(), cld);

        return bindStatementValue(stmt, index, crit.getAttribute(), crit.getValue2(), cld);
    }
103430
public boolean executeWithoutAccessCheck()
        throws EFapsException
    {
        boolean ret = false;
        if (isMarked4execute()) {
            if (getInstanceList().size() > 0) {
                ret = executeOneCompleteStmt(createSQLStatement(), this.allSelects);
            }
            if (ret) {
                for (final OneSelect onesel : this.allSelects) {
                    if (onesel.getFromSelect() != null) {
                        onesel.getFromSelect().execute(onesel);
                    }
                }
            }
        }
        return ret;
    }
873390
@Override
	public boolean doProcedure(final SqlContext sqlContext, final CallableStatement callableStatement,
			final boolean result) throws SQLException {
		if (getFilters().isEmpty()) {
			return result;
		}
		boolean rs = result;
		for (final SqlFilter filter : getFilters()) {
			rs = filter.doProcedure(sqlContext, callableStatement, rs);
		}
		return rs;
	}
2205
@Override
    public DataSet executeStatement(String stmt) throws JdbcServerException {
        log.info("Received execute statement request: " + stmt);
        Message response = handleMessageAndCheckResponse(JdbcMessage.execute(stmt));
        return dataSetCreator.createDataSet(response, getMessageType(response));
    }
449174
@Override
	public boolean execute(final LineReader reader, final String[] parts, final SqlConfig sqlConfig,
			final Properties props) {
		PrintWriter writer = reader.getTerminal().writer();
		if (parts.length >= 2) {
			String sqlName = parts[1].replaceAll("\\.", "/");
			if (sqlConfig.getSqlManager().existSql(sqlName)) {
				String sql = sqlConfig.getSqlManager().getSql(sqlName);
				String[] sqlLines = sql.split("\\r\\n|\\r|\\n");
				for (String sqlLine : sqlLines) {
					writer.println(sqlLine);
				}
			} else {
				writer.println("SQL not found. sql=" + sqlName);
			}
		}
		writer.flush();
		return true;
	}
760020
@Override
    public boolean execute(String sql) throws SQLException
    {
        checkClosed();
        VoltSQL query = VoltSQL.parseSQL(sql);
        return this.execute(query);
    }
988620
protected void executeSQL(String sql){
		Connection conn = null;
		Statement stmt = null;
		
		if (useAnt){
			try{
				AntSqlExec sqlExec = new AntSqlExec(dataSource, sql, delimiter, delimiterType);
				sqlExec.execute();
				log.info("SQL executed with Ant: " + sql);
			}catch(BuildException be){
				throw new RuntimeException("Failed to execute SQL with Ant (" + be.getMessage() + "): " + sql, be);
			}
		}else{
			try {
				conn = dataSource.getConnection();
				stmt = conn.createStatement();
				stmt.execute(sql);
				log.info("SQL executed: " + sql);
			}catch(SQLException sqle){
				throw new RuntimeException("Failed to execute SQL (" + sqle.getMessage() + "): " + sql, sqle);
			}finally{
				ConnectionUtility.closeConnection(conn, stmt);
			}
		}
	}
1049963
private void executeQuery(Subscriber<? super T> subscriber, State state) throws SQLException {
        if (!subscriber.isUnsubscribed()) {
            try {
                log.debug("executing sql={}, parameters {}", query.sql(), parameters);
                state.rs = query.resultSetTransform()
                        .call(query.context().resultSetTransform().call(state.ps.executeQuery()));
                log.debug("executed ps={}", state.ps);
            } catch (SQLException e) {
                throw new SQLException("failed to run sql=" + query.sql(), e);
            }
        }
    }
244719
public void execute(String statement) throws SQLException {
		if (logger.isDebugEnabled()) {
			logger.debug("Executing SQL statement [" + statement + "]");
		}
		
		Connection connection = null;
		Statement stm = null;
		
		try{
			connection = ds.getConnection();
			stm = connection.createStatement();			
			stm.execute(statement);
		} catch (SQLException e) {
			throw e;
		}finally{
			if(stm!=null) stm.close();
			if(connection!=null) connection.close();			
		}
				
	}
1288170
private void cmdExecuteActionPerformed(java.awt.event.ActionEvent evt) {
		releaseResultset();
		try {
			if (selectedSource == null) {
				JOptionPane.showMessageDialog(this, "Please select data source first", "Error", JOptionPane.ERROR_MESSAGE);
			} else {
				OBDAProgressMonitor progMonitor = new OBDAProgressMonitor("Executing query...", getRootPane());
				CountDownLatch latch = new CountDownLatch(1);
				ExecuteSQLQueryAction action = new ExecuteSQLQueryAction(latch);
				progMonitor.addProgressListener(action);
				progMonitor.start();
				action.run();
				latch.await();
				progMonitor.stop();
				ResultSet set = action.getResult();
				if (set != null) {
					ResultSetTableModel model = new ResultSetTableModel(set);
					tblQueryResult.setModel(model);
					set.close();
				}
			}
		} catch (Exception e) {
			OptionPaneUtils.showPrettyMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
			log.error("Error while executing query.", e);
		}
	}
647453
private void executeJdbcStatements(Connection connection, String configName, String statements, String description) {
        Statement stmt = createStatement(configName, connection);
        try {
            log.debug("Executing statement [" + description + "]");
            
            List<String> stmtsToExecute = Stream.of(statements.split(";"))
                    .map(String::trim)
                    .filter(s -> s.length() > 0)
                    .collect(Collectors.toList());
            
            if ( log.isTraceEnabled()) {
                log.trace("These statements will be executed:");
                stmtsToExecute.forEach(s -> log.trace("Statement: [" + s + "]"));
            }
            
            for ( String currentStatement : stmtsToExecute) {
                stmt.execute(currentStatement);
                log.trace("Executing statement: " + currentStatement + " OK!");
            }
            
        } catch (SQLException e) {
            throw new ChorusException(
                    String.format("Failed while executing statement [%s] on database + %s [%s]", description, configName, e.toString(), e)
            );
        }
    }
1129433
protected void execute(String sqlStatement, PrintWriter out, boolean acceptFailure) throws Exception {

        try (Connection conn = dataSource.getConnection()) {
            try (Statement stmt = conn.createStatement()) {

                boolean success = execute(stmt, sqlStatement, out, acceptFailure);

                // Loop over all kinds of results.
                while (success) { /* 'success' is not modified below this line */
                    int rowCount = stmt.getUpdateCount();

                    if (rowCount > 0) {
                        // --------------------------------------------------
                        // Result of successful INSERT or UPDATE or the like
                        // --------------------------------------------------
                        if (options.debug) {
                            out.println("Rows affected: " + rowCount);
                            out.flush();
                        }

                        if (stmt.getMoreResults()) {
                            continue;
                        }

                    } else if (rowCount == 0) {
                        // --------------------------------------------------
                        // Either a DDL command or 0 updates
                        // --------------------------------------------------
                        if (options.debug) {
                            out.println("No rows affected or statement was DDL command");
                            out.flush();
                        }

                        boolean moreResults;
                        try {
                            moreResults = stmt.getMoreResults();
                        } catch (SQLException sqle) {

                            // State: 24000 - Invalid cursor state
                            //  [Teradata: Continue request submitted but no response to return]
                            if (sqle.getSQLState().startsWith("24")) {
                                break;

                            } else {
                                throw sqle;
                            }
                        }
                        if (moreResults) {
                            continue;
                        }

                    } else { // rowCount < 0
                        // --------------------------------------------------
                        // Either we have a result set or no more results...
                        // --------------------------------------------------
                        ResultSet rs = stmt.getResultSet();
                        if (null != rs) {
                            // Ignore resultset
                            rs.close();

                            if (stmt.getMoreResults()) {
                                continue;
                            }
                        }
                    }

                    // No more results
                    break;
                }
            }
        } catch (SQLException sqle) {
            out.println("Failed to execute statement: \n" + sqlStatement);
            out.println("\n\nDescription of failure: \n" + Database.squeeze(sqle));
            out.flush();
            throw sqle;

        } catch (Exception e) {
            out.println("Failed to execute statement: \n" + sqlStatement);
            out.println("\n\nDescription of failure: \n" + e.getMessage());
            out.flush();
            throw e;
        }
    }
1040419
public static boolean queryHasResult(Statement stmt, String sql) {
    try {
      ResultSet rs = stmt.executeQuery(sql);
      try {
        return rs.next();
      } finally {
        rs.close();
      }
    } catch (SQLException e) {
      throw new DukeException(e);
    }
  }