Execute a SQL statement.

        The statement may be a string SQL string,
        an :func:`sqlalchemy.sql.expression.select` construct, or a 
        :func:`sqlalchemy.sql.expression.text` 
        construct.
433188
def execute(self, stmt, **params):
        
        return self.session.execute(sql.text(stmt, bind=self.bind), **params)
1101490
async def execute(self, sql: str, parameters: Iterable[Any] = None) -> None:
        """"""
        if parameters is None:
            parameters = []
        await self._execute(self._cursor.execute, sql, parameters)
534723
public int execute(String sql, Object... params) throws SQLException {
		Connection conn = null;
		try {
			conn = this.getConnection();
			return SqlExecutor.execute(conn, sql, params);
		} catch (SQLException e) {
			throw e;
		} finally {
			this.closeConnection(conn);
		}
	}
166024
def select(self, to_select, where=None, sql_params=None):
        '''
        
        '''
        if sql_params is None:
            sql_params = []
        query = '''
        SELECT %s FROM %s
        ''' % (to_select, self._name)
        if where:
            query = '%s WHERE %s' % (query, where)
        return self._cursor.execute(query, tuple(sql_params))
854801
def query(self, sql, param=None, stream=False, row_tuples=False):
        
        if not self.cursor:  # ALLOW NON-TRANSACTIONAL READS
            Log.error("must perform all queries inside a transaction")
        self._execute_backlog()

        try:
            if param:
                sql = expand_template(sql, quote_param(param))
            sql = self.preamble + outdent(sql)
            self.debug and Log.note("Execute SQL:\n{{sql}}", sql=indent(sql))

            self.cursor.execute(sql)
            if row_tuples:
                if stream:
                    result = self.cursor
                else:
                    result = wrap(list(self.cursor))
            else:
                columns = [utf8_to_unicode(d[0]) for d in coalesce(self.cursor.description, [])]
                if stream:
                    result = (wrap({c: utf8_to_unicode(v) for c, v in zip(columns, row)}) for row in self.cursor)
                else:
                    result = wrap([{c: utf8_to_unicode(v) for c, v in zip(columns, row)} for row in self.cursor])

            return result
        except Exception as e:
            e = Except.wrap(e)
            if "InterfaceError" in e:
                Log.error("Did you close the db connection?", e)
            Log.error("Problem executing SQL:\n{{sql|indent}}", sql=sql, cause=e, stack_depth=1)
820079
def execute(cur, sql):
    
    command, verbose, arg = parse_special_command(sql)

    if (command not in COMMANDS) and (command.lower() not in COMMANDS):
        raise CommandNotFound

    try:
        special_cmd = COMMANDS[command]
    except KeyError:
        special_cmd = COMMANDS[command.lower()]
        if special_cmd.case_sensitive:
            raise CommandNotFound('Command not found: %s' % command)

    # "help <SQL KEYWORD> is a special case.
    if command == 'help' and arg:
        return show_keyword_help(cur=cur, arg=arg)

    if special_cmd.arg_type == NO_QUERY:
        return special_cmd.handler()
    elif special_cmd.arg_type == PARSED_QUERY:
        return special_cmd.handler(cur=cur, arg=arg, verbose=verbose)
    elif special_cmd.arg_type == RAW_QUERY:
        return special_cmd.handler(cur=cur, query=sql)
333859
def execute_sql_statement(sql_statement, query, user_name, session, cursor):
    """"""
    database = query.database
    db_engine_spec = database.db_engine_spec
    parsed_query = ParsedQuery(sql_statement)
    sql = parsed_query.stripped()
    SQL_MAX_ROWS = app.config.get('SQL_MAX_ROW')

    if not parsed_query.is_readonly() and not database.allow_dml:
        raise SqlLabSecurityException(
            _('Only `SELECT` statements are allowed against this database'))
    if query.select_as_cta:
        if not parsed_query.is_select():
            raise SqlLabException(_(
                'Only `SELECT` statements can be used with the CREATE TABLE '
                'feature.'))
        if not query.tmp_table_name:
            start_dttm = datetime.fromtimestamp(query.start_time)
            query.tmp_table_name = 'tmp_{}_table_{}'.format(
                query.user_id, start_dttm.strftime('%Y_%m_%d_%H_%M_%S'))
        sql = parsed_query.as_create_table(query.tmp_table_name)
        query.select_as_cta_used = True
    if parsed_query.is_select():
        if SQL_MAX_ROWS and (not query.limit or query.limit > SQL_MAX_ROWS):
            query.limit = SQL_MAX_ROWS
        if query.limit:
            sql = database.apply_limit_to_sql(sql, query.limit)

    # Hook to allow environment-specific mutation (usually comments) to the SQL
    SQL_QUERY_MUTATOR = config.get('SQL_QUERY_MUTATOR')
    if SQL_QUERY_MUTATOR:
        sql = SQL_QUERY_MUTATOR(sql, user_name, security_manager, database)

    try:
        if log_query:
            log_query(
                query.database.sqlalchemy_uri,
                query.executed_sql,
                query.schema,
                user_name,
                __name__,
                security_manager,
            )
        query.executed_sql = sql
        with stats_timing('sqllab.query.time_executing_query', stats_logger):
            logging.info('Running query: \n{}'.format(sql))
            db_engine_spec.execute(cursor, sql, async_=True)
            logging.info('Handling cursor')
            db_engine_spec.handle_cursor(cursor, query, session)

        with stats_timing('sqllab.query.time_fetching_results', stats_logger):
            logging.debug('Fetching data for query object: {}'.format(query.to_dict()))
            data = db_engine_spec.fetch_data(cursor, query.limit)

    except SoftTimeLimitExceeded as e:
        logging.exception(e)
        raise SqlLabTimeoutException(
            "SQL Lab timeout. This environment's policy is to kill queries "
            'after {} seconds.'.format(SQLLAB_TIMEOUT))
    except Exception as e:
        logging.exception(e)
        raise SqlLabException(db_engine_spec.extract_error_message(e))

    logging.debug('Fetching cursor description')
    cursor_description = cursor.description
    return dataframe.SupersetDataFrame(data, cursor_description, db_engine_spec)
1024509
public int executeRaw(DatabaseConnection connection, String statement, String[] arguments) throws SQLException {
		logger.debug("running raw execute statement: {}", statement);
		if (arguments.length > 0) {
			// need to do the (Object) cast to force args to be a single object
			logger.trace("execute arguments: {}", (Object) arguments);
		}
		CompiledStatement compiledStatement = connection.compileStatement(statement, StatementType.EXECUTE,
				noFieldTypes, DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
		try {
			assignStatementArguments(compiledStatement, arguments);
			return compiledStatement.runExecute();
		} finally {
			IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
		}
	}
263773
public static <T> SQLQuery<T> select(Expression<T> expr) {
        return new SQLQuery<Void>().select(expr);
    }
871098
def execute(self, text, **params):
        """"""

        class UserDefinedType(sqlalchemy.TypeDecorator):
            """Add support for expandable values, a la https://github.com/sqlalchemy/sqlalchemy/issues/3953."""

            # Required class-level attribute
            # https://docs.sqlalchemy.org/en/latest/core/custom_types.html#sqlalchemy.types.TypeDecorator
            impl = sqlalchemy.types.UserDefinedType

            def process_literal_param(self, value, dialect):
                """Receive a literal parameter value to be rendered inline within a statement."""

                def process(value):
                    """Render a literal value, escaping as needed."""

                    # bool
                    if type(value) is bool:
                        return sqlalchemy.types.Boolean().literal_processor(dialect)(value)

                    # datetime.date
                    elif type(value) is datetime.date:
                        return sqlalchemy.types.String().literal_processor(dialect)(value.strftime("%Y-%m-%d"))

                    # datetime.datetime
                    elif type(value) is datetime.datetime:
                        return sqlalchemy.types.String().literal_processor(dialect)(value.strftime("%Y-%m-%d %H:%M:%S"))

                    # datetime.time
                    elif type(value) is datetime.time:
                        return sqlalchemy.types.String().literal_processor(dialect)(value.strftime("%H:%M:%S"))

                    # float
                    elif type(value) is float:
                        return sqlalchemy.types.Float().literal_processor(dialect)(value)

                    # int
                    elif type(value) is int:
                        return sqlalchemy.types.Integer().literal_processor(dialect)(value)

                    # long
                    elif sys.version_info.major != 3 and type(value) is long:
                        return sqlalchemy.types.Integer().literal_processor(dialect)(value)

                    # str
                    elif type(value) is str:
                        return sqlalchemy.types.String().literal_processor(dialect)(value)

                    # None
                    elif type(value) is sqlalchemy.sql.elements.Null:
                        return sqlalchemy.types.NullType().literal_processor(dialect)(value)

                    # Unsupported value
                    raise RuntimeError("unsupported value")

                # Process value(s), separating with commas as needed
                if type(value) is list:
                    return ", ".join([process(v) for v in value])
                else:
                    return process(value)

        # Allow only one statement at a time, since SQLite doesn't support multiple
        # https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.execute
        if len(sqlparse.split(text)) > 1:
            raise RuntimeError("too many statements at once")

        # Raise exceptions for warnings
        warnings.filterwarnings("error")

        # Prepare, execute statement
        try:

            # Construct a new TextClause clause
            statement = sqlalchemy.text(text)

            # Iterate over parameters
            for key, value in params.items():

                # Translate None to NULL
                if value is None:
                    value = sqlalchemy.sql.null()

                # Bind parameters before statement reaches database, so that bound parameters appear in exceptions
                # http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.text
                statement = statement.bindparams(sqlalchemy.bindparam(
                    key, value=value, type_=UserDefinedType()))

            # Stringify bound parameters
            # http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html#how-do-i-render-sql-expressions-as-strings-possibly-with-bound-parameters-inlined
            statement = str(statement.compile(compile_kwargs={"literal_binds": True}))

            # Statement for logging
            log = re.sub(r"\n\s*", " ", sqlparse.format(statement, reindent=True))

            # Execute statement
            result = self.engine.execute(statement)

            # If SELECT (or INSERT with RETURNING), return result set as list of dict objects
            if re.search(r"^\s*SELECT", statement, re.I):

                # Coerce any decimal.Decimal objects to float objects
                # https://groups.google.com/d/msg/sqlalchemy/0qXMYJvq8SA/oqtvMD9Uw-kJ
                rows = [dict(row) for row in result.fetchall()]
                for row in rows:
                    for column in row:
                        if type(row[column]) is decimal.Decimal:
                            row[column] = float(row[column])
                ret = rows

            # If INSERT, return primary key value for a newly inserted row
            elif re.search(r"^\s*INSERT", statement, re.I):
                if self.engine.url.get_backend_name() in ["postgres", "postgresql"]:
                    result = self.engine.execute(sqlalchemy.text("SELECT LASTVAL()"))
                    ret = result.first()[0]
                else:
                    ret = result.lastrowid

            # If DELETE or UPDATE, return number of rows matched
            elif re.search(r"^\s*(?:DELETE|UPDATE)", statement, re.I):
                ret = result.rowcount

            # If some other statement, return True unless exception
            else:
                ret = True

        # If constraint violated, return None
        except sqlalchemy.exc.IntegrityError:
            self.logger.debug(termcolor.colored(log, "yellow"))
            return None

        # If user errror
        except sqlalchemy.exc.OperationalError as e:
            self.logger.debug(termcolor.colored(log, "red"))
            e = RuntimeError(self._parse(e))
            e.__cause__ = None
            raise e

        # Return value
        else:
            self.logger.debug(termcolor.colored(log, "green"))
            return ret
183325
def exec_query(sql, name = 'SQL', binds = [])
      # NOTE: we allow to execute SQL as requested returning a results.
      # e.g. this allows to use SQLServer's EXEC with a result set ...
      sql = to_sql(sql, binds) if sql.respond_to?(:to_sql)

      sql = repair_special_columns(sql)
      if prepared_statements?
        log(sql, name, binds) { @connection.execute_query(sql, binds) }
      else
        log(sql, name) { @connection.execute_query(sql) }
      end
    end
876094
def execute(self, sql, param=(), times=1):
        
        self.log and self.log.debug('%s %s' % ('SQL:', sql))
        if param is not ():
            self.log and self.log.debug('%s %s' % ('PARAMs:', param))
        for i in xrange(times):
            try:
                ret, res = self._execute(sql, param)
                return ret, res
            except Exception, e:
                self.log and self.log.warn("The %s time execute, fail" % i)
                self.log and self.log.warn(e)
            if i: sleep(i**1.5)
        self.log and self.log.error(e)
        return None, e
128296
def db_exec_literal(self, sql: str) -> int:
        """"""
        self.ensure_db_open()
        cursor = self.db.cursor()
        debug_sql(sql)
        try:
            cursor.execute(sql)
            return cursor.rowcount
        except:  # nopep8
            log.exception("db_exec_literal: SQL was: " + sql)
            raise
843646
def executeBatch(cursor, sql,
                 regex=r"(?mx) ([^';]* (?:'[^']*'[^';]*)*)",
                 comment_regex=r"(?mx) (?:^\s*$)|(?:--.*$)"):
    
    # First, strip comments
    sql = "\n".join([x.strip().replace("%", "%%") for x in re.split(comment_regex, sql) if x.strip()])

    # Stored procedures don't work with the above regex because many of them are
    # made up multiple sql statements each delimited with a single ;
    # where the regexes assume each statement delimited by a ; is a complete
    # statement to send to mysql and execute.
    #
    # Here i'm simply checking for the delimiter statements (which seem to be
    # mysql-only) and then using them as markers to start accumulating statements.
    # So the first delimiter is the signal to start accumulating
    # and the second delimiter is the signal to combine them into
    # single sql compound statement and send it to mysql.

    in_proc = False
    statements = []

    for st in re.split(regex, sql)[1:][::2]:
        if st.strip().lower().startswith("delimiter"):
            in_proc = not in_proc
            if statements and not in_proc:
                procedure = ";".join(statements)
                statements = []
                cursor.execute(procedure)
            # skip the delimiter line
            continue

        if in_proc:
            statements.append(st)
        else:
            cursor.execute(st)
687080
public int execute(String sql, List<Object> params) {
        return this.execute(sql, params.toArray());
    }
1060113
def execute(self, sql, parameters = None, cursorClass = DictCursor, quiet = False, locked = False, do_commit = True):
		""""""
		i = 0
		errcode = 0
		caughte = None
		cursor = None
		if sql.find(";") != -1 or sql.find("\\G") != -1:
			# Catches some injections
			raise Exception("The SQL command '%s' contains a semi-colon or \\G. This is a potential SQL injection." % sql)
		while i < self.numTries:
			i += 1
			try:
				assert(not(self.connection) or not(self.connection.open))
				self._get_connection(cursorClass)
				cursor = self.connection.cursor()
				if locked:
					cursor.execute(self.lockstring)
					self.locked = True
				if parameters:
					errcode = cursor.execute(sql, parameters)
				else:
					errcode = cursor.execute(sql)
				self.lastrowid = int(cursor.lastrowid)
				if do_commit and self.isInnoDB:
					self.connection.commit()
				results = cursor.fetchall()
				if locked:
					cursor.execute(self.unlockstring)
					self.locked = False
				cursor.close()
				self._close_connection()
				return results
			except MySQLdb.OperationalError, e:
				if cursor:
					if self.locked:
						cursor.execute(self.unlockstring)
						self.locked = False
					cursor.close()
				self._close_connection()
				caughte = str(e)
				errcode = e[0]
				continue
			except Exception, e:
				if cursor:
					if self.locked:
						cursor.execute(self.unlockstring)
						self.locked = False
					cursor.close()
				self._close_connection()
				caughte = str(e)
				traceback.print_exc()
				break
			sleep(0.2)
		
		if not quiet:
			sys.stderr.write("\nSQL execution error in query %s at %s:" % (sql, datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
			sys.stderr.write("\nErrorcode/Error: %d - '%s'.\n" % (errcode, str(caughte)))
			sys.stderr.flush()
		raise MySQLdb.OperationalError(caughte)
670550
function executeQuery () {
    return this.model.mysql().query(this.select.sql, this.select.params)
    // decode data
    .then(results => {
        // decode any encoded data columns
        return this.decodeData(results)
    })
    // add custom error handler
    .catch(err => {
        throw this.error('db error', err)
    })
}