Executes an SQL SELECT query and returns rows generator.

        :param sql: query to execute
        :param args: parameters iterable
        :param kwargs: parameters iterable
        :return: rows generator
        :rtype: generator
968144
def query(self, sql, *args, **kwargs):
        
        with self.locked() as conn:
            for row in conn.query(sql, *args, **kwargs):
                yield row
1337542
def _sql(self, sql: str, params=()):
        
        statement = SingleSqlStatement(sql)
        return self.statement(statement).execute_for_params(params).cursor
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()
1269673
def execute(self, sql, parameters=None, bulk_parameters=None):
        
        if self.connection._closed:
            raise ProgrammingError("Connection closed")

        if self._closed:
            raise ProgrammingError("Cursor closed")

        self._result = self.connection.client.sql(sql, parameters,
                                                  bulk_parameters)
        if "rows" in self._result:
            self.rows = iter(self._result["rows"])
1043651
async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:
        """"""
        await self._execute(self._cursor.executemany, sql, parameters)
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
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)
1230361
public ResultSet executeQuery(String sql) throws SQLException {
    if (executeInternal(sql, fetchSize, Statement.NO_GENERATED_KEYS)) {
      return results.getResultSet();
    }
    return SelectResultSet.createEmptyResultSet();
  }
525780
def compile(self):
        
        params = self.column_params + self.join_params + self.params
        if self.limit and self.limit >= 0:
            self.sql_limit = 'LIMIT ?'
            params += [self.limit]
        return (self.sql, params, self.keys)
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)
155894
public List<List<Object>> queryResults(String sql, String[] args) {
		return db.queryResults(sql, args);
	}
76319
def _select_sql(self, **kwargs):
        
        return 'SELECT {distinct}{modifier}{select}'.format(
              distinct='DISTINCT ' if self._distinct else '',
              modifier='{} '.format(' '.join(self._modifiers)) if self._modifiers else '',
              select=','.join(term.get_sql(with_alias=True, subquery=True, **kwargs)
                              for term in self._selects),
        )
501355
def generate(args=None, namespace=None, file=None):
    
    if hasattr(args, 'split'):
        args = args.split()
    args = parser.parse_args(args, namespace)
    set_logging(args)
    logging.info(str(args))
    if args.dialect in ('pg', 'pgsql', 'postgres'):
        args.dialect = 'postgresql'
    if args.dialect.startswith('dj'):
        args.dialect = 'django'
    elif args.dialect.startswith('sqla'):
        args.dialect = 'sqlalchemy'

    if args.dialect not in dialect_names:
        raise NotImplementedError('First arg must be one of: %s' % ", ".join(dialect_names))
    if args.dialect == 'sqlalchemy':
        print(sqla_head, file=file)
    for datafile in args.datafile:
        if is_sqlalchemy_url.search(datafile):
            table_names_for_insert = []
            for tbl in sqlalchemy_table_sources(datafile):
                t = generate_one(tbl, args, table_name=tbl.generator.name, file=file)
                if t.data:
                    table_names_for_insert.append(tbl.generator.name)
            if args.inserts and args.dialect == 'sqlalchemy':
                print(sqla_inserter_call(table_names_for_insert), file=file)
            if t and args.inserts:
                for seq_update in emit_db_sequence_updates(t.source.db_engine):
                    if args.dialect == 'sqlalchemy':
                        print('    conn.execute("%s")' % seq_update, file=file)
                    elif args.dialect == 'postgresql':
                        print(seq_update, file=file)
        else:
            generate_one(datafile, args, file=file)
920424
def get_sql(query):
    
    sql = str(query.statement.compile(dialect=sqlite.dialect(),
                                      compile_kwargs={"literal_binds": True}))
    return sql
979005
def selectSQL(conn, sql, args=None):
    '''
    
    '''
    with doCursor(conn) as cursor:
        cursor.execute(sql, args)
        results = cursor.fetchall()
        return results
478387
def fetchall(self, sql: str, *args) -> Sequence[Sequence[Any]]:
        """"""
        self.ensure_db_open()
        cursor = self.db.cursor()
        self.db_exec_with_cursor(cursor, sql, *args)
        try:
            rows = cursor.fetchall()
            return rows
        except:  # nopep8
            log.exception("fetchall: SQL was: " + sql)
            raise
1000068
def sql(self, sql: str, *qmark_params, **named_params):
        
        statement = SingleSqlStatement(sql)
        return self.statement(statement).execute(*qmark_params, **named_params)