Invokes the JDBC Query.
If QueryType is Select, returns a java.sql.ResultSet.
If QueryType is Update, returns an Integer with the number of rows updated.
487539
public Object invoke(Object conn, Object requestData) throws AdapterException {
        try {
            DatabaseAccess dbAccess = (DatabaseAccess)conn;
            if (requestData == null)
                throw new AdapterException("Missing SQL Query");
            String query = (String) requestData;
            QueryType queryType = getQueryType();

            Object queryParams = getQueryParameters();
            if (queryParams instanceof List<?>) {
                if (queryType == QueryType.Select)
                    return dbAccess.runSelect(query, ((List<?>) queryParams).toArray());
                else if (queryType == QueryType.Update) {
                    Integer ret = new Integer(dbAccess.runUpdate(query, ((List<?>)queryParams).toArray()));
                    dbAccess.commit();
                    return ret;
                }
                else
                    throw new AdapterException("Unsupported query type: " + queryType);
            }
            else {
                if (queryType == QueryType.Select)
                    return dbAccess.runSelect(query, queryParams);
                else if (queryType == QueryType.Update) {
                    Integer ret = new Integer(dbAccess.runUpdate(query, queryParams));
                    dbAccess.commit();
                    return ret;
                }
                else
                    throw new AdapterException("Unsupported query type: " + queryType);
            }
        }
        catch (SQLException ex) {
            AdapterException adapEx = new AdapterException(-1, ex.getMessage(), ex);
            if (isRetryable(ex))
              adapEx.setRetryable(true);
            throw adapEx;
        }
        catch (Exception ex) {
            throw new AdapterException(-1, ex.getMessage() , ex);
        }
    }
322769
@When("^I query the database with '(.+?)'$")
    public void selectData(String query) throws Exception {
        Statement myStatement = null;
        //postgres table
        List<String> sqlTable = new ArrayList<String>();
        List<String> sqlTableAux = new ArrayList<String>();
        Connection myConnection = this.commonspec.getConnection();
        java.sql.ResultSet rs = null;
        try {
            myStatement = myConnection.createStatement();
            rs = myStatement.executeQuery(query);
            //column names
            ResultSetMetaData resultSetMetaData = rs.getMetaData();
            int count = resultSetMetaData.getColumnCount();
            for (int i = 1; i <= count; i++) {
                sqlTable.add(resultSetMetaData.getColumnName(i).toString());
            }
            //takes column names and column count
            while (rs.next()) {
                for (int i = 1; i <= count; i++) {
                    //aux list without column names
                    sqlTableAux.add(rs.getObject(i).toString());
                }
            }
            sqlTable.addAll(sqlTableAux);

            //sends raws to environment variable
            for (int i = 0; i < sqlTable.size(); i++) {
                ThreadProperty.set("queryresponse" + i, sqlTable.get(i));
            }
            ThreadProperty.remove("queryresponse" + sqlTable.size());
            rs.close();
            myStatement.close();
        } catch (Exception e) {
            e.printStackTrace();
            Assertions.assertThat(rs).as("There are no response from SELECT").isNotNull();
        }
    }
1084144
public List<QueryResult> executeQuery() throws SQLException {
        final boolean isExceptionThrown = ExecutorExceptionHandler.isExceptionThrown();
        SQLExecuteCallback<QueryResult> executeCallback = new SQLExecuteCallback<QueryResult>(getDatabaseType(), isExceptionThrown) {
            
            @Override
            protected QueryResult executeSQL(final RouteUnit routeUnit, final Statement statement, final ConnectionMode connectionMode) throws SQLException {
                return getQueryResult(routeUnit, statement, connectionMode);
            }
        };
        return executeCallback(executeCallback);
    }
299433
public int executeUpdate() throws SQLException {
        return executeUpdate(new Updater() {
            
            @Override
            public int executeUpdate(final Statement statement, final String sql) throws SQLException {
                return statement.executeUpdate(sql);
            }
        });
    }
212659
public ResultSetAndStatement executeQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("executeQuery: " + query);
        }
        /*
		 * MBAIRD: we should create a scrollable resultset if the start at
		 * index or end at index is set
		 */
        boolean scrollable = ((query.getStartAtIndex() > Query.NO_START_AT_INDEX) || (query.getEndAtIndex() > Query.NO_END_AT_INDEX));
        /*
		 * OR if the prefetching of relationships is being used.
		 */
        if (query != null && query.getPrefetchedRelationships() != null && !query.getPrefetchedRelationships().isEmpty())
        {
            scrollable = true;
        }
        final StatementManagerIF sm = broker.serviceStatementManager();
        final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectStatement(query, cld);
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try
        {
            final int queryFetchSize = query.getFetchSize();
            final boolean isStoredProcedure = isStoredProcedure(sql.getStatement());
            stmt = sm.getPreparedStatement(cld, sql.getStatement() ,
                    scrollable, queryFetchSize, isStoredProcedure);
            if (isStoredProcedure)
            {
                // Query implemented as a stored procedure, which must return a result set.
                // Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}
                getPlatform().registerOutResultSet((CallableStatement) stmt, 1);
                sm.bindStatement(stmt, query, cld, 2);

                if (logger.isDebugEnabled())
                    logger.debug("executeQuery: " + stmt);

                stmt.execute();
                rs = (ResultSet) ((CallableStatement) stmt).getObject(1);
            }
            else
            {
                sm.bindStatement(stmt, query, cld, 1);

                if (logger.isDebugEnabled())
                    logger.debug("executeQuery: " + stmt);

                rs = stmt.executeQuery();
            }

            return new ResultSetAndStatement(sm, stmt, rs, sql);
        }
        catch (PersistenceBrokerException e)
        {
            // release resources on exception
            sm.closeResources(stmt, rs);
            logger.error("PersistenceBrokerException during the execution of the query: " + e.getMessage(), e);
            throw e;
        }
        catch (SQLException e)
        {
            // release resources on exception
            sm.closeResources(stmt, rs);
            throw ExceptionHelper.generateException(e, sql.getStatement(), null, logger, null);
        }
    }
1048076
public int executeUpdate(String sql) throws SQLException {
    if (executeInternal(sql, fetchSize, Statement.NO_GENERATED_KEYS)) {
      return 0;
    }
    return getUpdateCount();
  }
6170
public static ResultSet callQuery(Connection conn, String sql, Object... params) throws SQLException {
		CallableStatement proc = null;
		try {
			proc = StatementUtil.prepareCall(conn, sql, params);
			return proc.executeQuery();
		} finally {
			DbUtil.close(proc);
		}
	}
235034
public Query execute(PageContext pc, SQL sql, int maxrows, int fetchsize, TimeSpan timeout) throws PageException {
	Stopwatch stopwatch = new Stopwatch(Stopwatch.UNIT_NANO);
	stopwatch.start();
	String prettySQL = null;
	Selects selects = null;

	// First Chance
	try {
	    SelectParser parser = new SelectParser();
	    selects = parser.parse(sql.getSQLString());

	    Query q = qoq.execute(pc, sql, selects, maxrows);
	    q.setExecutionTime(stopwatch.time());

	    return q;
	}
	catch (SQLParserException spe) {
	    // lucee.print.printST(spe);
	    // sp
	    // lucee.print.out("sql parser crash at:");
	    // lucee.print.out("--------------------------------");
	    // lucee.print.out(sql.getSQLString().trim());
	    // lucee.print.out("--------------------------------");
	    // print.e("1:"+sql.getSQLString());
	    prettySQL = SQLPrettyfier.prettyfie(sql.getSQLString());
	    // print.e("2:"+prettySQL);
	    try {
		Query query = executer.execute(pc, sql, prettySQL, maxrows);
		query.setExecutionTime(stopwatch.time());
		return query;
	    }
	    catch (PageException ex) {
		// lucee.print.printST(ex);
		// lucee.print.out("old executor/zql crash at:");
		// lucee.print.out("--------------------------------");
		// lucee.print.out(sql.getSQLString().trim());
		// lucee.print.out("--------------------------------");

	    }

	}
	catch (PageException e) {
	    // throw e;
	    // print.out("new executor crash at:");
	    // print.out("--------------------------------");
	    // print.out(sql.getSQLString().trim());
	    // print.out("--------------------------------");
	}
	// if(true) throw new RuntimeException();

	// SECOND Chance with hsqldb
	try {
	    boolean isUnion = false;
	    Set<String> tables = null;
	    if (selects != null) {
		HSQLUtil2 hsql2 = new HSQLUtil2(selects);
		isUnion = hsql2.isUnion();
		tables = hsql2.getInvokedTables();
	    }
	    else {
		if (prettySQL == null) prettySQL = SQLPrettyfier.prettyfie(sql.getSQLString());
		HSQLUtil hsql = new HSQLUtil(prettySQL);
		tables = hsql.getInvokedTables();
		isUnion = hsql.isUnion();
	    }

	    String strSQL = StringUtil.replace(sql.getSQLString(), "[", "", false);
	    strSQL = StringUtil.replace(strSQL, "]", "", false);
	    sql.setSQLString(strSQL);
	    return _execute(pc, sql, maxrows, fetchsize, timeout, stopwatch, tables, isUnion);

	}
	catch (ParseException e) {
	    throw new DatabaseException(e.getMessage(), null, sql, null);
	}

    }
516106
public int update(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {
		try {
			// there is always and id field as an argument so just return 0 lines updated
			if (argFieldTypes.length <= 1) {
				return 0;
			}
			Object[] args = getFieldObjects(data);
			Object newVersion = null;
			if (versionFieldType != null) {
				newVersion = versionFieldType.extractJavaFieldValue(data);
				newVersion = versionFieldType.moveToNextValue(newVersion);
				args[versionFieldTypeIndex] = versionFieldType.convertJavaFieldToSqlArgValue(newVersion);
			}
			int rowC = databaseConnection.update(statement, args, argFieldTypes);
			if (rowC > 0) {
				if (newVersion != null) {
					// if we have updated a row then update the version field in our object to the new value
					versionFieldType.assignField(connectionSource, data, newVersion, false, null);
				}
				if (objectCache != null) {
					// if we've changed something then see if we need to update our cache
					Object id = idField.extractJavaFieldValue(data);
					T cachedData = objectCache.get(clazz, id);
					if (cachedData != null && cachedData != data) {
						// copy each field from the updated data into the cached object
						for (FieldType fieldType : tableInfo.getFieldTypes()) {
							if (fieldType != idField) {
								fieldType.assignField(connectionSource, cachedData,
										fieldType.extractJavaFieldValue(data), false, objectCache);
							}
						}
					}
				}
			}
			logger.debug("update data with statement '{}' and {} args, changed {} rows", statement, args.length, rowC);
			if (args.length > 0) {
				// need to do the (Object) cast to force args to be a single object
				logger.trace("update arguments: {}", (Object) args);
			}
			return rowC;
		} catch (SQLException e) {
			throw SqlExceptionUtil.create("Unable to run update stmt on object " + data + ": " + statement, e);
		}
	}
691573
@Nullable
    public T query() throws SQLException {
        try (ResultSet r = executeQuery()) {
            if (r.next()) {
                return resultMapper.map(r);
            }
            return null;
        }
    }
164288
public int executeUpdateDeleteQuery(String cqlQuery) {
        if (log.isDebugEnabled()) {
            log.debug("Executing cql query {}.", cqlQuery);
        }
        try {
            CqlResult result = (CqlResult) executeCQLQuery(cqlQuery, true);
            return result.getNum();
        } catch (Exception e) {
            log.error("Error while executing updated query: {}, Caused by: . ", cqlQuery, e);
            return 0;
        }

    }
128025
@Override
	public int doUpdate(final SqlContext sqlContext, final PreparedStatement preparedStatement, final int result) {
		LOG.debug("SQL:{} executed. Count:{} items.", sqlContext.getSqlName(), result);
		return result;
	}
1092345
public static int executeUpdate(final String sql, final Object... args)
    {
       return SqlClosure.sqlExecute(c -> executeUpdate(c, sql, args));
    }
1227415
public int update() throws SQLException {
		checkForDao();
		@SuppressWarnings("unchecked")
		T t = (T) this;
		return dao.update(t);
	}
569573
@NotNull
    public T queryNN() throws SQLException {
        T res = null;
        try (ResultSet r = statement.executeQuery()) {
            if (r.next()) {
                res = resultMapper.map(r);
            }
            Objects.requireNonNull(res);
            return res;
        }
    }
844322
@Override
    public ResultSet getTypeInfo() throws SQLException
    {
        checkClosed();
        this.sysCatalog.setString(1, "TYPEINFO");
        ResultSet res = this.sysCatalog.executeQuery();
        return res;
    }
1349768
@Override
    public int executeUpdate(String updateSql) throws JdbcServerException {
        log.info("Received execute update request: " + updateSql);
        Message response = handleMessageAndCheckResponse(JdbcMessage.execute(updateSql));
        return Optional.ofNullable(
                response.getHeader(JdbcMessageHeaders.JDBC_ROWS_UPDATED))
                .map(Object::toString).map(Integer::valueOf)
                .orElse(0);
    }