Executes a query that returns a single record. In the case of no result, rather than throwing
an exception, null is returned.
@param q Query to Execute
@return T The instance to return, or null if no result.
428342
protected T getSingleResult(Query q) {
		try {
			@SuppressWarnings("unchecked")
			T retVal = (T) q.getSingleResult();
			return retVal;
		} catch (NoResultException e) {
			return null;
		}
	}
646695
public V get ()
        throws SQLException
    {
        V result = next();
        if (result != null) {
            int spurious = 0;
            while (next() != null) {
                spurious++;
            }
            if (spurious > 0) {
                log.warning("Cursor.get() quietly tossed " + spurious + " spurious additional " +
                            "records.", "query", _query);
            }
        }
        return result;
    }
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);
    }
  }
797674
def ExecuteQuery(self, query, args=None):
    """"""

    def Action(connection):
      connection.cursor.execute(query, args)
      rowcount = connection.cursor.rowcount
      results = connection.cursor.fetchall()
      return results, rowcount

    return self._RetryWrapper(Action)
698454
public CountQueryResult executeCount() {
		CountQueryResult ret = new CountQueryResult(this);
		Object so = this.queryExecutor.getMappingInfo().getInternalDomainAccess().getSyncObject();
		if (so != null) {
			synchronized (so) {
				this.queryExecutor.executeCount();
			}
		} else
			this.queryExecutor.executeCount();
		return ret;
	}
565550
protected final <T> T executeQuery(final String sql, final StatementWithReturnBlock<T> queryBlock) throws Exception {
        checkState(initialized);

        setupConnection();
        checkNotNull(connection);
        boolean committed = false;
        try {
            T returnValue = withStatement(connection, sql, queryBlock);
            connection.commit();
            committed = true;
            return returnValue;
        } finally {
            if (!committed) {
                connection.rollback();
                cleanupConnection();
            }
        }
    }
5131
private ResultSet executeCQL(String cql) {
        m_logger.debug("Executing CQL: {}", cql);
        try {
            return m_dbservice.getSession().execute(cql);
        } catch (Exception e) {
            m_logger.error("CQL query failed", e);
            m_logger.info("   Query={}", cql);
            throw e;
        }
    }
511899
public <T> T executeQuery(@NotNull ResultSetProcessor<T> processor, @NotNull SqlQuery query) {
        return withCurrentTransaction(query, tx -> {
            logQuery(query);

            try (PreparedStatement ps = tx.getConnection().prepareStatement(query.getSql())) {
                prepareStatementFromQuery(ps, query);

                long startTime = currentTimeMillis();
                try (ResultSet resultSet = ps.executeQuery()) {
                    logQueryExecution(query, currentTimeMillis() - startTime);
                    return processor.process(resultSet);
                }
            }
        });
    }
946651
public QueryResult execute(Query query) throws QueryEngineException {
        if (!(query instanceof QueryImpl)) {
            throw new QueryEngineException("Couldn't cast Query to QueryImpl.");
        }
        QueryImpl q = (QueryImpl) query;


        // search for unbound results vars
        resvarsLoop:
        for (QueryArgument arg : q.getResultVars()) {
            for (QueryAtomGroup g : q.getAtomGroups()) {
                for (QueryAtom a : g.getAtoms()) {
                    if (a.getArguments().contains(arg)) {
                        continue resvarsLoop;
                    }
                }
            }
//			throw new QueryEngineException("Query contains an unbound result argument " + arg + ".");
        }

        Queue<QueryResultImpl> results = new LinkedList<>();
        for (QueryAtomGroup g : q.getAtomGroups()) {

            QueryAtomGroupImpl group = (QueryAtomGroupImpl) g;

            List<QueryAtomGroupImpl> components = findComponents(group);
            Queue<QueryResultImpl> componentResults = new LinkedList<>();
            boolean groupAsk = true;
            for (QueryAtomGroupImpl component : components) {

                QueryAtomGroupImpl preorderedGroup = preorder(component);

                QueryResultImpl result = new QueryResultImpl(query);
                if (eval(q, preorderedGroup, result, new QueryBindingImpl(), BoundChecking.CHECK_BOUND)) {
                    if (query.isSelectDistinct()) {
                        result = eliminateDuplicates(result);
                    }

                    componentResults.add(result);
                }
                else {
                    groupAsk = false;
                    break;
                }
            }

            if (groupAsk) {
                results.add(combineResults(componentResults,
                                           query.getType() == SELECT_DISTINCT));
            }
            else {
                // return only empty result with no solution for this group
                QueryResultImpl ret = new QueryResultImpl(query);
                ret.setAsk(false);
                results.add(ret);
            }
        }

        return unionResults(q, results, query.getType() == SELECT_DISTINCT);
    }
122004
public PaginatedResult execute(final Query query) {
        final long count = getCount(query);
        decorate(query);
        return new PaginatedResult()
                .objects(query.execute())
                .total(count);
    }
1248685
def execute(self, q, args=()):
        
        # pylint:disable=too-many-branches
        self.rowcount = None
        response = None
        if self.query is None:
            self.execute_select(q, args)
        else:
            response = self.execute_django(q, args)
            if isinstance(response, list):
                return

        # the encoding is detected automatically, e.g. from headers
        if response and response.text:
            # parse_float set to decimal.Decimal to avoid precision errors when
            # converting from the json number to a float and then to a Decimal object
            # on a model's DecimalField. This converts from json number directly
            # to a Decimal object
            data = response.json(parse_float=decimal.Decimal)
            # a SELECT query
            if 'totalSize' in data:
                # SELECT
                self.rowcount = data['totalSize']
            # a successful INSERT query, return after getting PK
            elif('success' in data and 'id' in data):
                self.lastrowid = data['id']
                return
            elif 'compositeResponse' in data:
                # TODO treat error reporting for composite requests
                self.lastrowid = [x['body']['id'] if x['body'] is not None else x['referenceId']
                                  for x in data['compositeResponse']]
                return
            elif data['hasErrors'] is False:
                # it is from Composite Batch request
                # save id from bulk_create even if Django don't use it
                if data['results'] and data['results'][0]['result']:
                    self.lastrowid = [item['result']['id'] for item in data['results']]
                return
            # something we don't recognize
            else:
                raise DatabaseError(data)

            if not q.upper().startswith('SELECT COUNT() FROM'):
                self.first_row = data['records'][0] if data['records'] else None
1053602
@Override
	public final ResultSet executeQuery() throws SQLException {
		Split split = prepare();
		try {
			return new SimonResultSet(stmt.executeQuery(), this, prefix, split.getStopwatch().getName());
		} finally {
			finish(split);
		}
	}
929511
private <T> TypedQuery<T> onTypedQuery(Class<T> paramClass, Query q)
    {
        if (paramClass.equals(((QueryImpl) q).getKunderaQuery().getEntityClass()) || paramClass.equals(Object.class))
        {
            return new KunderaTypedQuery<T>(q);
        }

        throw new IllegalArgumentException("Mismatch in expected return type. Expected:" + paramClass
                + " But actual class is:" + ((QueryImpl) q).getKunderaQuery().getEntityClass());
    }
586170
public Api getQueryResult(String query) throws Exception {
    Api result = this.getActionResult("query", query, null, null);
    return result;
  }
1036266
public QueryCommand query() {
        QueryCommand result = new Query(source, constraint, orderings, columns, limit, distinct);
        if (this.firstQuery != null) {
            // EXCEPT has a higher precedence than INTERSECT or UNION, so if the first query is
            // an INTERSECT or UNION SetQuery, the result should be applied to the RHS of the previous set ...
            if (firstQuery instanceof SetQuery && firstQuerySetOperation == Operation.EXCEPT) {
                SetQuery setQuery = (SetQuery)firstQuery;
                QueryCommand left = setQuery.getLeft();
                QueryCommand right = setQuery.getRight();
                SetQuery exceptQuery = new SetQuery(right, Operation.EXCEPT, result, firstQueryAll);
                result = new SetQuery(left, setQuery.operation(), exceptQuery, setQuery.isAll());
            } else {
                result = new SetQuery(this.firstQuery, this.firstQuerySetOperation, result, this.firstQueryAll);
            }
        }
        return result;
    }
1080906
public Object execute(AbstractEbeanQuery query, Object[] values) {
        Assert.notNull(query, "AbstractEbeanQuery must not be null!");
        Assert.notNull(values, "Values must not be null!");

        return doExecute(query, values);
    }
738113
@Override
    public <T> T query(MonetaryQuery<T> query) {
        Objects.requireNonNull(query);
        try {
            return query.queryFrom(this);
        } catch (MonetaryException | ArithmeticException e) {
            throw e;
        } catch (Exception e) {
            throw new MonetaryException("Query failed: " + query, e);
        }
    }