Switch to the desired database, execute query, and switch
back again (if needed)
496435
public function query($query_text,$whichCon='',$params=false)
    {
        $current = $this->connection->defaultDatabase($whichCon);
        $this->connection->selectDB($this->dbName, $whichCon);
        $ret = $this->connection->query($query_text, $whichCon='', $params);
        if ($current) {
            $this->connection->selectDB($current, $whichCon);
        }

        return $ret;
    }
310624
def _get_query(self, callback, schema, query=None, *args, **kwargs):
        """"""
        if not query: query = Query()

        ret = None
        with self.connection(**kwargs) as connection:
            kwargs['connection'] = connection
            try:
                if connection.in_transaction():
                    # we wrap SELECT queries in a transaction if we are in a transaction because
                    # it could cause data loss if it failed by causing the db to discard
                    # anything in the current transaction if the query isn't wrapped,
                    # go ahead, ask me how I know this
                    with self.transaction(**kwargs):
                        ret = callback(schema, query, *args, **kwargs)

                else:
                    ret = callback(schema, query, *args, **kwargs)

            except Exception as e:
                exc_info = sys.exc_info()
                if self.handle_error(schema, e, **kwargs):
                    ret = callback(schema, query, *args, **kwargs)
                else:
                    self.raise_error(e, exc_info)

        return ret
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);
    });
}
1086133
def reset(c7n_async=None):
    
    click.echo('Delete db? Are you Sure? [yn] ', nl=False)
    c = click.getchar()
    click.echo()
    if c == 'y':
        click.echo('Wiping database')
        worker.connection.flushdb()
    elif c == 'n':
        click.echo('Abort!')
    else:
        click.echo('Invalid input :(')
274855
def load
      query = (arguments or self).info_sql
      Squirm.exec(query, [name, schema]) do |result|
        validate result
        set_values_from result
      end
      self
    end
869599
def execute(self, sql, values = ()) :
		""
		sql = sql.strip()
		self._debugActions(sql, values)
		cur = self.connection.cursor()
		cur.execute(sql, values)
		return cur
691368
def db_remove(database_name, **kwargs):
    '''
    
    '''
    try:
        if db_exists(database_name, **kwargs) and database_name not in ['master', 'model', 'msdb', 'tempdb']:
            conn = _get_connection(**kwargs)
            conn.autocommit(True)
            cur = conn.cursor()
            cur.execute('ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE'.format(database_name))
            cur.execute('DROP DATABASE {0}'.format(database_name))
            conn.autocommit(False)
            conn.close()
            return True
        else:
            return False
    except Exception as e:
        return 'Could not find the database: {0}'.format(e)
1173894
def __execute_text(self, query, **replacements):
        

        # We've had persistent and long-term issues where we can't access tables 
        # from another client because they're locked, as well as getting the 
        # "gone away" error quite frequenctly. Per the documentation, apparently 
        # it is common to -not- reuse the same session from request to request,
        # and we believe this to be the problem. Hopefully it's fixed, now.
        #
        # REF: http://docs.sqlalchemy.org/en/rel_0_9/orm/session.html#when-do-i-construct-a-session-when-do-i-commit-it-and-when-do-i-close-it
        session = self.__get_session()
        
        try:
            records = session.execute(query, replacements)
        except:
            _LOGGER.exception("Query failure:\n%s", query)

            raise

        # Verifying that we have a realized list of results before we commit 
        # the transaction.

        try:
            records = list(records)
        finally:
            session.commit()

        for record in records:
            yield dict(record)
667650
function execute() {
		try {

			// we need to bind in order
			if (empty($this->refactored_stmt)) {
				$index = [];

				$this->refactored_stmt = $this->query;

				# 
				# We need to sort by length to avoid replacing keys that are
				# prefixes of other keys, thereby invaliding the bigger keys
				#

				$keylengths = [];
				foreach (\array_keys($this->params) as $key) {
					$keylengths[$key] = strlen($key);
				}

				\asort($keylengths, SORT_NUMERIC);

				$keys = \array_keys(\array_reverse($keylengths, true));

				foreach ($keys as $key) {
					$position = \strpos($this->query, $key);
					if ($position == false) {
						throw new Panic("Tried to bind parameter $key but it's not present in statement.");
					}

					$this->refactored_stmt = \str_replace($key, '?', $this->refactored_stmt);

					$index[$key] = $position;
				}

				\asort($index, SORT_NUMERIC);

				$this->stmt = \mysqli_prepare($this->dbh, $this->refactored_stmt);

				if ( ! $this->stmt) {
					throw new Panic('Failed to prepare statement');
				}

				$bindings = '';
				$args = [ $this->stmt, null ];
				foreach (array_keys($index) as $key) {
					$bindings .= $this->params[$key][1];
					$args[] = & $this->params[$key][0];
				}

				$args[1] = $bindings;

				if ( ! empty($args[1])) {
					\call_user_func_array('mysqli_stmt_bind_param', $args);
				}
			}
			
			if ( ! \mysqli_stmt_execute($this->stmt)) {
				throw new Panic('Failed to execute statement');
			}

			#
			# to avoid complications with statements not getting closed before
			# new ones are executed we fetch the result set imediatly
			#

			$this->resultset = [];
			$result = \mysqli_stmt_get_result($this->stmt);
			while ($data = mysqli_fetch_assoc($result)) {
				$this->resultset[] = $data;
			}
		}
		catch (\Exception $exception) {
			$message = $exception->getMessage();
			$message .= "\n".$this->formatQuery($this->query);
			throw new Panic($message, 500, $exception);
		}

		return $this;
	}
475041
def execute(self, conn, data_tier_name='', transaction = False, cache=None):
        
	if cache:
            ret=cache.get("DATA_TIERS")
            if not ret==None:
                return ret
        sql = self.sql
	binds={}
	if data_tier_name:
            op = ('=', 'like')['%' in data_tier_name]
	    sql += "WHERE DT.DATA_TIER_NAME %s :datatier" %op 
	    binds = {"datatier":data_tier_name}
        result = self.dbi.processData(sql, binds, conn, transaction)
        plist = self.formatDict(result)
        return plist
820171
def execute(*args, **kwargs):
        

        # Inspect the call stack for the originating call
        args = CoyoteDb.__add_query_comment(args[0])
        db = CoyoteDb.__get_db_write_instance(target_database=kwargs.pop('target_database', None))
        filtered_kwargs = {k: v for k, v in kwargs.iteritems() if k != 'target_database'}

        # Execute the query
        cursor = db.cursor()
        try:
            cursor.execute(*args, **filtered_kwargs)
        except OperationalError, e:
            raise OperationalError('{} when executing: {}'.format(e.args, args[0]))
        return db, cursor
33741
def init(context, reset, force):
    """"""
    existing_tables = context.obj['store'].engine.table_names()
    if force or reset:
        if existing_tables and not force:
            message = f"Delete existing tables? [{', '.join(existing_tables)}]"
            click.confirm(click.style(message, fg='yellow'), abort=True)
        context.obj['store'].drop_all()
    elif existing_tables:
        click.echo(click.style("Database already exists, use '--reset'", fg='red'))
        context.abort()

    context.obj['store'].setup()
    message = f"Success! New tables: {', '.join(context.obj['store'].engine.table_names())}"
    click.echo(click.style(message, fg='green'))
26571
function SelectDB($dbName)
	{
		$this->database = $dbName;
		$this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions
		$try = $this->Execute('use ' . $dbName);
		return ($try !== false);
	}
767314
def execute(self, query, *parameters, **kwargs):
        """"""
        cursor = self._cursor()
        try:
            self._execute(cursor, query, parameters, kwargs)

        except:
            raise

        finally:
            cursor.close()
362522
def reset(self):
        
        query = """
            DROP TABLE identifier_index;
        """
        self.backend.library.database.connection.execute(query)
1274799
def execute(self, conn, dataset="",  logical_file_name="", app="", release_version="", pset_hash="", 
                output_label ="", block_id=0, global_tag='', transaction = False):
        
	#sql=self.sql	
        binds = {}
	setAnd=False
	#add search only block id only for migration dump block. 
	if block_id==0:
	    sql = self.sql1 + self.sql2
	    if dataset:
		sql += " JOIN %sDATASET_OUTPUT_MOD_CONFIGS DC ON DC.OUTPUT_MOD_CONFIG_ID=O.OUTPUT_MOD_CONFIG_ID" % self.owner
		sql += " JOIN %sDATASETS DS ON DS.DATASET_ID=DC.DATASET_ID" % self.owner
	    if logical_file_name:
		sql += " JOIN %sFILE_OUTPUT_MOD_CONFIGS FC ON FC.OUTPUT_MOD_CONFIG_ID=O.OUTPUT_MOD_CONFIG_ID" % self.owner
		sql += " JOIN %sFILES FS ON FS.FILE_ID=FC.FILE_ID" % self.owner
	    if not app == "":
		op = ("=", "like")["%" in app]
		sql += " WHERE A.APP_NAME %s :app_name" % op
        	binds["app_name"]=app
		setAnd=True
	    if not release_version == "":
		op = ("=", "like")["%" in release_version]
		if setAnd : sql += " AND " 
		else : sql += " WHERE "
		sql += " R.RELEASE_VERSION %s :release_version" % op
		binds["release_version"]=release_version
		setAnd=True
	    if not pset_hash == "":
		op = ("=", "like")["%" in pset_hash]
		if setAnd : sql += " AND "
		else : sql += " WHERE "
		sql += " P.PSET_HASH %s :pset_hash" % op
		binds["pset_hash"]=pset_hash
		setAnd=True
	    if not output_label == "":
		op = ("=", "like")["%" in output_label]
                if setAnd : sql += " AND "
		else : sql += " WHERE "
	        sql += " O.OUTPUT_MODULE_LABEL %s :output_module_label" % op
	        binds["output_module_label"]=output_label
		setAnd=True
            if not global_tag == "":
                op = ("=", "like")["%" in global_tag]
                if setAnd : sql += " AND "
                else : sql += " WHERE "
                sql += " O.GLOBAL_TAG %s :global_tag" % op
                binds["global_tag"]=global_tag
                setAnd=True
	    if dataset:
		if setAnd : sql += " AND "
		else : sql += " WHERE "
		sql += "DS.DATASET=:dataset"
		binds["dataset"]=dataset
		setAnd=True
	    if logical_file_name:
		if setAnd : sql += " AND "
		else : sql += " WHERE "
		sql += "FS.LOGICAL_FILE_NAME=:logical_file_name"
		binds["logical_file_name"]=logical_file_name
		setAnd=True
	else:
	    #select by block id and return config along with LFN
	    sql=  self.sql1 + " , FS.LOGICAL_FILE_NAME LFN " +  self.sql2 \
	          + " JOIN %sFILE_OUTPUT_MOD_CONFIGS FC ON FC.OUTPUT_MOD_CONFIG_ID=O.OUTPUT_MOD_CONFIG_ID" % self.owner \
		  +  " JOIN %sFILES FS ON FS.FILE_ID=FC.FILE_ID" % self.owner \
		  +  "  WHERE FS.BLOCK_ID = :block_id "
	    binds["block_id"]=block_id
	cursors = self.dbi.processData(sql, binds, conn, transaction=False, returnCursor=True)
	#assert len(cursors) == 1, "output module config does not exist"
        result = []
	for c in cursors:
            result.extend(self.formatCursor(c, size=100))
        return result
64281
def execute_sql(self, query):
        
        c = self.con.cursor()
        c.execute(query)
        result = c.fetchall()
        return result