Run query with prepared statements.
199020
private function implementPrepareStatements()
    {
        $this->response = $this->provider->statements(
            $this->query,
            $this->settings['statements']
        );
    }
1267293
public function exec(): void
    {
        $this->queryExecuted = false;
        $sql = $this->getSQL();
        $adapter = $this->getAdapter();

        $adapter->prepare($sql);
        $bindings = $this->getBindings();

        try {
            foreach ($bindings->getBindings() as $bind) {
	            $adapter->getStatement()->bindValue($bind->getParameter(), $bind->getValue(), $bind->getType());
            }

	        $adapter->getStatement()->execute();

            Log::sql("{$this->adapter}>>>\n{$this->debug()}");
        } catch (PDOException $e) {
            // more descriptive error handling when query fails

            switch ($e->getCode()) {
                case 'HY093': // PDO miss match parameter count
                    //Log::debug("[{$e->getCode()}] Tried and failed to execute SQL query:\n{$sql}");
                    //Log::debug('BINDINGS', $bindings->getAsArray());
	                $exception = new QueryException("[{$e->getCode()}] Query bindings parameter miss match: {$e->getMessage()}", (int) $e->getCode(), $e);
                    break;

                default:
                    //Log::debug("[{$e->getCode()}] Tried and failed to execute SQL query:\n{$this->debug()}");
	                $exception = new QueryException("[{$e->getCode()}] Tried and failed to execute SQL query: {$e->getMessage()}", (int) $e->getCode(), $e);
                    break;
            }

            $exception->setAdapter($adapter->getConfigKey());
	        $exception->setSql($this->debug());
	        $exception->setBindings($bindings);
	        $exception->setWasPrepared(true);
            throw $exception;
        }

        $this->queryExecuted = true;
    }
1304606
function runQuery(query, connection) {
  const { maxRows } = connection;
  const limit = maxRows < CRATE_LIMIT ? maxRows : CRATE_LIMIT;

  if (connection.port) {
    crate.connect(connection.host, connection.port);
  } else {
    crate.connect(connection.host);
  }

  return crate
    .execute(query)
    .then(res => {
      const results = {
        rows: res.json,
        incomplete: false
      };

      if (results.rows.length >= limit) {
        results.incomplete = true;
        results.rows = results.rows.slice(0, limit);
      }

      return results;
    })
    .catch(err => {
      throw new Error(err.message);
    });
}
240207
def _loadDB(self):
        """"""
        if not self._validID():
            raise NotFound, self._getID()
        (sql, fields) = self._prepareSQL("SELECT")
        curs = self.cursor()
        curs.execute(sql, self._getID())
        result = curs.fetchone()
        if not result:
            curs.close()
            raise NotFound, self._getID()
        self._loadFromRow(result, fields, curs)
        curs.close()
        self._updated = time.time()
1237818
def _prepare(self, query):
        
        self._logger.info(u'Prepare a statement: [{}]'.format(query))

        # Send Parse message to server
        # We don't need to tell the server the parameter types yet
        self.connection.write(messages.Parse(self.prepared_name, query, param_types=()))
        # Send Describe message to server
        self.connection.write(messages.Describe('prepared_statement', self.prepared_name))
        self.connection.write(messages.Flush())

        # Read expected message: ParseComplete
        self._message = self.connection.read_expected_message(messages.ParseComplete, self._error_handler)

        # Read expected message: ParameterDescription
        self._message = self.connection.read_expected_message(messages.ParameterDescription, self._error_handler)
        self._param_metadata = self._message.parameters

        # Read expected message: RowDescription or NoData
        self._message = self.connection.read_expected_message(
                        (messages.RowDescription, messages.NoData), self._error_handler)
        if isinstance(self._message, messages.NoData):
            self.description = None # response was NoData for a DDL/transaction PreparedStatement
        else:
            self.description = [Column(fd, self.unicode_error) for fd in self._message.fields]

        # Read expected message: CommandDescription
        self._message = self.connection.read_expected_message(messages.CommandDescription, self._error_handler)
        if len(self._message.command_tag) == 0:
            msg = 'The statement being prepared is empty'
            self._logger.error(msg)
            self.connection.write(messages.Sync())
            raise errors.EmptyQueryError(msg)

        self._logger.info('Finish preparing the statement')
770474
protected function prepare()
        {
            if (!Core::getDBlink() instanceof \PDO) {
                throw new Exception('Connection not up, can\'t prepare the statement');
            }

            $this->statement = Core::getDBlink()->prepare($this->query->getSql());
        }
116460
def _run_queries(self, queries, *args, **kwargs):
        
        # write out all the commands to a temp file and then have psql run that file
        f = self._get_file()
        for q in queries:
            f.write("{};\n".format(q))
        f.close()

        psql_args = self._get_args('psql', '-X', '-f {}'.format(f.name))
        return self._run_cmd(' '.join(psql_args), *args, **kwargs)
1297904
function runQuery(query, connection) {
  const config = {
    user: connection.username,
    password: connection.password,
    connection_string: connection.connection_string
  };
  // TODO use connection pool
  // TODO handle connection.maxRows

  let cn = config.connection_string;

  // Not all drivers require auth
  if (config.user) {
    cn = cn + ';Uid=' + config.user;
  }
  if (config.password) {
    cn = cn + ';Pwd=' + config.password;
  }

  return openConnection(cn)
    .then(() => executeQuery(query))
    .then(queryResult => {
      odbc.close(); // TODO consider putting into finally()?
      return Promise.resolve({ rows: queryResult, incomplete: false });
    })
    .catch(function(e) {
      console.error(e, e.stack);
    });
}
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)
17563
public function run($sql, $bind = "")
    {
        $this->_sql = trim($sql);
        $this->_bind = $this->cleanup($bind);
        $this->_error = "";

        try {
            $start = microtime(true);
            $pdostmt = $this->prepare($this->_sql);
            if ($pdostmt->execute($this->_bind) !== false) {
                if (preg_match("/^(" . implode("|", array("select", "describe", "pragma")) . ") /i", $this->_sql))
                {
                    $return = ($this->limit == 1)? $pdostmt->fetch(\PDO::FETCH_ASSOC) : $pdostmt->fetchAll(\PDO::FETCH_ASSOC);
                }
                elseif (preg_match("/^(" . implode("|", array("delete", "update")) . ") /i", $this->_sql))
                {
                    $return = $pdostmt->rowCount();
                }
                elseif (preg_match("/^(" . implode("|", array("insert")) . ") /i", $this->_sql))
                {
                    $return = $this->lastInsertId();
                }
            }


            if ($this->print) {
                $time = microtime(true) - $start;
                $queryPreview = $this->interpolateQuery($this->_sql, $this->_bind);
                print_r($queryPreview);
            }

            return $return;

        } catch (PDOException $e) {
            $this->_error = $e->getMessage();
            if($this->print) {
                $queryPreview = $this->interpolateQuery($this->_sql, $this->_bind);
                print_r($queryPreview);
            }
            $this->debug();
            return false;
        }
    }
612871
def query(self, sql: str, args: tuple = None):
        """"""

        with self._cursor() as cursor:
            log.debug('Running SQL: ' + str((sql, args)))
            cursor.execute(sql, args)
            return cursor.fetchall()
1221127
def _execute(self):
        """"""

        query = [
            'gerrit', 'query',
            '--current-patch-set',
            str(self._filters),
            '--format=JSON']

        results = self.client.exec_command(' '.join(query))
        stdin, stdout, stderr = results

        for line in stdout:
            normalized = json.loads(line)

            # Do not return the last item
            # since it is the summary of
            # of the query
            if "rowCount" in normalized:
                raise StopIteration

            yield normalized
1217191
public function run_query($sql, array $params=null, array $driverOptions=array()) {
		try {
			$this->sth = null;
			$this->sth = $this->dbh->prepare($sql, $driverOptions);
			if($this->sth === false) {
				throw new \Exception(__METHOD__ .": STH is false... ". ToolBox::debug_print($this->dbh->errorInfo(),0));
			}
			// TODO: throw an exception on error (and possibly if there were no rows returned)
			$this->sth->execute($params); 
			$this->numRows = $this->sth->rowCount();
		}
		catch(PDOException $px) {
			throw new \Exception(__METHOD__ .": ". $px->getMessage());
		}
		return($this->numRows);
	}
510893
private void proceedWithQuery
  (PreparedStatement queryStmt, DataSet ds) throws SQLException {
    if (queryArgs != null && queryArgs.length > 0) {
      for (int i=0; i < queryArgs.length; i++) {
        queryStmt.setObject(i + 1, queryArgs[i]);
      }
    }
    try(ResultSet rs = queryStmt.executeQuery()) {
      int colCount = metaData.getColumnCount();
      while (rs.next()) {
        Object[] data = new Object[colCount];
        for (int i = 0; i < colCount; i++) {  
          data[i] = rs.getObject(i+1);
        }
        ds.addRow(new Row(data));
      }
    }
  }
56337
def execute_sql_statements(
    ctask, query_id, rendered_query, return_results=True, store_results=False,
    user_name=None, session=None, start_time=None,
):
    """"""
    if store_results and start_time:
        # only asynchronous queries
        stats_logger.timing(
            'sqllab.query.time_pending', now_as_float() - start_time)

    query = get_query(query_id, session)
    payload = dict(query_id=query_id)
    database = query.database
    db_engine_spec = database.db_engine_spec
    db_engine_spec.patch()

    if store_results and not results_backend:
        raise SqlLabException("Results backend isn't configured.")

    # Breaking down into multiple statements
    parsed_query = ParsedQuery(rendered_query)
    statements = parsed_query.get_statements()
    logging.info(f'Executing {len(statements)} statement(s)')

    logging.info("Set query to 'running'")
    query.status = QueryStatus.RUNNING
    query.start_running_time = now_as_float()

    engine = database.get_sqla_engine(
        schema=query.schema,
        nullpool=True,
        user_name=user_name,
        source=sources.get('sql_lab', None),
    )
    # Sharing a single connection and cursor across the
    # execution of all statements (if many)
    with closing(engine.raw_connection()) as conn:
        with closing(conn.cursor()) as cursor:
            statement_count = len(statements)
            for i, statement in enumerate(statements):
                # TODO CHECK IF STOPPED
                msg = f'Running statement {i+1} out of {statement_count}'
                logging.info(msg)
                query.set_extra_json_key('progress', msg)
                session.commit()
                try:
                    cdf = execute_sql_statement(
                        statement, query, user_name, session, cursor)
                    msg = f'Running statement {i+1} out of {statement_count}'
                except Exception as e:
                    msg = str(e)
                    if statement_count > 1:
                        msg = f'[Statement {i+1} out of {statement_count}] ' + msg
                    payload = handle_query_error(msg, query, session, payload)
                    return payload

    # Success, updating the query entry in database
    query.rows = cdf.size
    query.progress = 100
    query.set_extra_json_key('progress', None)
    query.status = QueryStatus.SUCCESS
    if query.select_as_cta:
        query.select_sql = database.select_star(
            query.tmp_table_name,
            limit=query.limit,
            schema=database.force_ctas_schema,
            show_cols=False,
            latest_partition=False)
    query.end_time = now_as_float()

    payload.update({
        'status': query.status,
        'data': cdf.data if cdf.data else [],
        'columns': cdf.columns if cdf.columns else [],
        'query': query.to_dict(),
    })

    if store_results:
        key = str(uuid.uuid4())
        logging.info(f'Storing results in results backend, key: {key}')
        with stats_timing('sqllab.query.results_backend_write', stats_logger):
            json_payload = json.dumps(
                payload, default=json_iso_dttm_ser, ignore_nan=True)
            cache_timeout = database.cache_timeout
            if cache_timeout is None:
                cache_timeout = config.get('CACHE_DEFAULT_TIMEOUT', 0)
            results_backend.set(key, zlib_compress(json_payload), cache_timeout)
        query.results_key = key
    session.commit()

    if return_results:
        return payload
686562
public static function run($query, $params=array()) {
		
		$self = static::getInstance();
		
		$self->openConnection();
		
		$ret = NULL;
		
		try {
			
			// prepare query
			$stat = $self->handler->prepare($query);

			// bind parameters
			$stat->execute((array)$params);

			// count affected rows
			$affected = $stat->rowCount();
			
		} catch (\PDOException $e) {
			
			// logger
			$self->logParamQuery($query, 0, $params);
			
			switch ($e->getCode()) {
				
				// integrity constraint violation
				/*
				 case '23000':
					 $message = 'Database integrity constraint violation';
					 break;
				 */
				default:
					$message = $e->getMessage();
					break;
			}
			
			$self->addError($message);
			
			$affected = 0;
			
		} catch (\Exception $e) {
			
			// logger
			$self->logParamQuery($query, 0, $params);
			$self->addError($e->getMessage());
			$affected = 0;
			
		}
		
		$stat->closeCursor();
		$self->logParamQuery($query, $affected, $params);
		
		return $affected;
			
	}
313127
public function execute()
	{
		$this->connect();

		// Take a local copy so that we don't modify the original query and cause issues later
		$sql = $this->replacePrefix((string) $this->sql);

		if ($this->limit > 0 || $this->offset > 0)
		{
			$sql = $this->limit($sql, $this->limit, $this->offset);
		}

		// Increment the query counter.
		$this->count++;

		// If debugging is enabled then let's log the query.
		if ($this->debug)
		{
			// Add the query to the object queue.
			$this->log(
				Log\LogLevel::DEBUG,
				'{sql}',
				array('sql' => $sql, 'category' => 'databasequery', 'trace' => debug_backtrace())
			);
		}

		// Reset the error values.
		$this->errorNum = 0;
		$this->errorMsg = '';

		$options = array();

		// SQLSrv_num_rows requires a static or keyset cursor.
		if (strncmp(strtoupper(ltrim($sql)), 'SELECT', \strlen('SELECT')) === 0)
		{
			$options = array('Scrollable' => SQLSRV_CURSOR_KEYSET);
		}

		$params = array();

		// Bind the variables:
		if ($this->sql instanceof PreparableInterface)
		{
			$bounded =& $this->sql->getBounded();

			if (\count($bounded))
			{
				foreach ($bounded as $key => $obj)
				{
					// And add the value as an additional param
					$params[] = $obj->value;
				}
			}
		}

		// Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost.
		$this->cursor = @sqlsrv_query($this->connection, $sql, $params, $options);

		// If an error occurred handle it.
		if (!$this->cursor)
		{
			// Check if the server was disconnected.
			if (!$this->connected())
			{
				try
				{
					// Attempt to reconnect.
					$this->connection = null;
					$this->connect();
				}
				catch (ConnectionFailureException $e)
				{
					// If connect fails, ignore that exception and throw the normal exception.
					$errors         = sqlsrv_errors();
					$this->errorNum = $errors[0]['code'];
					$this->errorMsg = $errors[0]['message'];

					// Throw the normal query exception.
					$this->log(
						Log\LogLevel::ERROR,
						'Database query failed (error #{code}): {message}; Failed query: {sql}',
						array('code' => $this->errorNum, 'message' => $this->errorMsg, 'sql' => $sql)
					);

					throw new ExecutionFailureException($sql, $this->errorMsg, $this->errorNum);
				}

				// Since we were able to reconnect, run the query again.
				return $this->execute();
			}

			// The server was not disconnected.
			$errors         = sqlsrv_errors();
			$this->errorNum = $errors[0]['code'];
			$this->errorMsg = $errors[0]['message'];

			// Throw the normal query exception.
			$this->log(
				Log\LogLevel::ERROR,
				'Database query failed (error #{code}): {message}; Failed query: {sql}',
				array('code' => $this->errorNum, 'message' => $this->errorMsg, 'sql' => $sql)
			);

			throw new ExecutionFailureException($sql, $this->errorMsg, $this->errorNum);
		}

		return $this->cursor;
	}