Возвращает строки ответа, полученного через query

        > db.query('SELECT * FORM users WHERE id=:id', {"id":MY_USER_ID})

        :param command: SQL запрос
        :param params: Параметры для prepared statements
        :rtype: list of dict
513832
def all(self, command, params=None):
        
        dr = self.query(command, params)
        return dr['rows']
67140
def _query(self, query_str, query_args=None, **query_options):
        
        ret = True
        # http://stackoverflow.com/questions/6739355/dictcursor-doesnt-seem-to-work-under-psycopg2
        connection = query_options.get('connection', None)
        with self.connection(connection) as connection:
            cur = connection.cursor()
            ignore_result = query_options.get('ignore_result', False)
            count_result = query_options.get('count_result', False)
            one_result = query_options.get('fetchone', query_options.get('one_result', False))
            cursor_result = query_options.get('cursor_result', False)

            try:
                if query_args:
                    self.log("{}{}{}", query_str, os.linesep, query_args)
                    cur.execute(query_str, query_args)
                else:
                    self.log(query_str)
                    cur.execute(query_str)

                if cursor_result:
                    ret = cur

                elif not ignore_result:
                    if one_result:
                        ret = self._normalize_result_dict(cur.fetchone())
                    elif count_result:
                        ret = cur.rowcount
                    else:
                        ret = self._normalize_result_list(cur.fetchall())

            except Exception as e:
                self.log(e)
                raise

            return ret
43267
@SafeVarargs
  public static Query query(DB db, String sql, Object... args) {
    return new Query(db, sql, args);
  }
125462
def by_id(cls, user_id, db_session=None):
        
        db_session = get_db_session(db_session)
        query = db_session.query(cls.model)
        query = query.filter(cls.model.id == user_id)
        query = query.options(sa.orm.eagerload("groups"))
        return query.first()
1183139
function (connectionInfo, query, params) {
    var connection;

    // Connection validation
    if (typeof connectionInfo.host !== 'string' || connectionInfo.host.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'Bad hostname provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }
    if (typeof connectionInfo.user !== 'string' || connectionInfo.user.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'Bad username provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }

    if (typeof connectionInfo.password !== 'string') {
        return respond({
            success: false,
            data: {
                err: 'Bad password provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }
    if (typeof connectionInfo.database !== 'string' || connectionInfo.database.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'Bad database provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }


    // Return if no sql query specified
    if (query.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'No SQL query specified.'
            }
        });
    }

    // Create the connection to the database
    connection = mysql.createConnection(connectionInfo);

    // Connect to the database
    connection.connect();

    // Do the query
    connection.query(query, params, function (err, rows, fields) {
        // End the connection
        connection.end();

        // Return the error and stop
        if (err) {
            return respond({
                success: false,
                data: {
                    err: err,
                    query: query,
                    connection: connectionInfo
                }

            });
        }

        // Do the callback
        respond({
            success: true,
            data: {
                rows: rows,
                fields: fields
            }
        });
    });
}
398029
def sql(self, sql, params=()):
        ''' 
        '''
        def _items(items):
            for item in items:
                yield self._item_class(item)

        sql = sql.strip()
        try:
            self._cursor.execute(sql, params)
        except sqlite3.OperationalError, err:
            raise SQLError('%s, SQL: %s, params: %s' % (err, sql, params) )
        except sqlite3.IntegrityError:
            raise DuplicateItem('Duplicate item, %s' % item)

        if sql.upper().startswith('SELECT'):
            return _items(self._cursor.fetchall())
        else:
            return None
1205239
def query_args(self, name):
        
        sql = 'select type, id from code_items ' \
              'where kind = 22 and name = ?'
        logging.debug('%s %s', sql, (name,))
        self.cursor.execute(sql, (name,))
        func = self.cursor.fetchone()
        if func:
            sql = 'select param_number, type, name ' \
                  'from code_items where parent_id = ?'
            logging.debug('%s %s', sql, (func[1],))
            self.cursor.execute(sql, (func[1],))
            args = self.cursor.fetchall()
            ret_type = clean_ret_type(func[0])
            args = [
                (arg_number, sanitize_type(arg_type), arg_name)
                for arg_number, arg_type, arg_name in args
            ]
            return ret_type, name, args
        return None
553802
def user_query(username, email):
    
    query = db.query(User)
    if username:
        query = query.filter_by(username=username)

    if email:
        query = query.filter_by(username=username)

    return query
406940
private CommandOutput<?, ?> executePreparedSql(List<Command> cmds) {
    String query = null;
    List<String> queryParameters = null;
    int fetchSize = 0;

    for (Command cmd : cmds) {
      if (cmd instanceof JdbcCommand) {
        JdbcCommandType type = (JdbcCommandType) cmd.getCommandType();
        switch (type) {
          case QUERY:
            query = cmd.getParams().get(0);
            break;
          case QUERYPARAMS:
            queryParameters = cmd.getParams();
            break;
          case FETCHSIZE:
            fetchSize = Integer.parseInt(cmd.getParams().get(0));
            break;
          default:
            this.log.error("Command " + type.toString() + " not recognized");
            break;
        }
      }
    }

    this.log.info("Executing query:" + query);
    ResultSet resultSet = null;
    try {
      this.jdbcSource = createJdbcSource();
      if (this.dataConnection == null) {
        this.dataConnection = this.jdbcSource.getConnection();
      }

      PreparedStatement statement =
          this.dataConnection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);

      int parameterPosition = 1;
      if (queryParameters != null && queryParameters.size() > 0) {
        for (String parameter : queryParameters) {
          statement.setString(parameterPosition, parameter);
          parameterPosition++;
        }
      }
      if (fetchSize != 0) {
        statement.setFetchSize(fetchSize);
      }
      final boolean status = statement.execute();
      if (status == false) {
        this.log.error("Failed to execute sql:" + query);
      }
      resultSet = statement.getResultSet();

    } catch (Exception e) {
      this.log.error("Failed to execute sql:" + query + " ;error-" + e.getMessage(), e);
    }

    CommandOutput<JdbcCommand, ResultSet> output = new JdbcCommandOutput();
    output.put((JdbcCommand) cmds.get(0), resultSet);
    return output;
  }
1326158
function (req, res) {

            req.params.table = escape(req.params.table);

            //Request DB structure
            lastQry = connection.query('SHOW COLUMNS FROM ??', req.params.table, function (err, columns) {

                //Get primary key of table if not specified via query
                var field = findPrim(columns, req.query[settings.paramPrefix + 'field']);

                lastQry = connection.query('SELECT * FROM ?? WHERE ??.?? IN (' + req.params.id + ')', [req.params.table, req.params.table, field], function (err, rows) {
                    if (err) return sendError(res, err.code);
                    res.send({
                        result: 'success',
                        json: rows,
                        table: req.params.table,
                        length: rows.length
                    });
                });
            });

        }
223457
public static void command(final ODatabaseObject db, final String command, final Object... args) {
        db.command(new OCommandSQL(String.format(command, args))).execute();
    }
412919
private Sql getPreperSQLWithParameters(String query, Map<String, Object> parameters) {
		// 检索query语句中所有:key的标记
		Pattern pattern = Pattern.compile(":\\w+");
		Matcher matcher = pattern.matcher(query);

		// 构建<key, index>值对
		int index = 1;
		Map<String, Integer> keyIndexs = new HashMap<String, Integer>();
		while (matcher.find()) {
			String word = matcher.group();
			if (word.startsWith(":")) {
				keyIndexs.put(word.substring(1), index++);
			}
		}

		// 构建<index, value>值对
		Map<Integer, Object> prepareValue = new HashMap<Integer, Object>();
		Set<String> paramKeySet = parameters.keySet();
		for (String paramKey : paramKeySet) {
			Integer preIndex = keyIndexs.get(paramKey);
			Object preValue = parameters.get(paramKey);

			prepareValue.put(preIndex, preValue);
		}

		// 替换所有的变量为"?"
		query = matcher.replaceAll("?");

		Sql sql = new Sql(query, parameters);
		sql.setPreperStatement(true);
		sql.setKeyIndexs(keyIndexs);
		sql.setPreperValues(prepareValue);

		return sql;
	}
1217732
def __preparequery(self, sql_query, columns):
        
        if columns:
            if "${columns}" not in sql_query:
                raise TypeError("received columns but ${columns} not in query")

            escape = self.__methods[METHOD_ESCAPE]

            self.__col2idx_map = {}
            col_list = []

            for idx, col in enumerate(columns):
                self.__col2idx_map[col] = idx
                col_list.append(escape(col))

            return sql_query.replace("${columns}", ",".join(col_list))
        else:
            self.__col2idx_map = None

            return sql_query
374542
def _make_sql_params(self,kw):
        """"""
        vals = []
        for k,v in kw.iteritems():
            vals.append('%s=%s' %(k,self._conv(v)))
        return vals
1240798
def handle(self, *args, **options):
        

        def get_user(username):
            try:
                return User.objects.get(username=username)
            except ObjectDoesNotExist as e:
                raise CommandError("This user doesn't exist in the database")

        def get_fields_permissions(user):
            try:
                return UserFieldPermissions.objects.get(user=user)
            except ObjectDoesNotExist as e:
                raise CommandError("This user doesn't have fields permissions")



        if len(args) !=1:
            raise CommandError("Specifies a user")
        else:
            try:
                self.stdout.ending = None
                user = get_user(args[0])
                fields_permissions  = get_fields_permissions(user)
                permissions = fields_permissions.permissions.all()

                jsoneatthat = {'username': user.username, 
                    'fields_permissions' : [ {'app_label': permission.content_type.app_label, 'model' : permission.content_type.model, 'name': permission.name } for permission in permissions]}

                self.stdout.write(json.dumps(jsoneatthat))

            except:
                raise
701263
def data_from_query(self, cmd):
        
        res  = None
        ckey = "%s /%s" % (self.command, cmd)

        if not isinstance(self._query_params, dict):
            self._query_params = {}

        if ckey in _NCMD:
            self._cmd = _NCMD[ckey]
        else:
            for key in sorted(_RCMD, key=len, reverse=True):
                if not key.startswith("%s " % self.command):
                    continue

                m = _RCMD[key].name.match(cmd)
                if m:
                    self._cmd = _RCMD[key]
                    self._query_params.update(m.groupdict())
                    break

        try:
            if not self._cmd:
                raise self.req_error(404)

            if not self._cmd.to_log:
                self._to_log = False

            if self._cmd.to_auth:
                self.authenticate(self._cmd.auth_users)

            if self._cmd.static:
                if self._cmd.handler:
                    res = self._cmd.handler(self)

                return self.static_file(cmd, res)

            res = self._cmd.handler(self)

            if not isinstance(res, HttpResponse):
                return self.response_dumps(res)

            return res
        finally:
            self._query_params = {}
328774
function selectByIdWhereSql () {
    // get id column
    var idColumn = this.model.columnName('id')
    // every where statement will begin with the alias and column name
    var columnSql = `${this.alias}.${this.quoteName(idColumn)}`
    // sql for where query
    var sql
    // if ids are array build in query
    if (Array.isArray(this.args.where.id)) {
        var i = 0
        // get placeholder for each in value
        var placeholders = _.map(this.args.where.id, id => {
            // get param name
            var paramName = `id${i}`
            // increment param counter
            i++
            // set value for param placeholder
            this.params[paramName] = id
            // create placeholder
            return this.unhexId(`:${paramName}`)
        })
        // return where sql
        sql = `WHERE ${columnSql} IN(${placeholders.join(', ')})`
    }
    // otherwise build equals query
    else {
        // set value for param placeholder
        this.params.id = this.args.where.id
        // get place holder
        var placeholder = this.unhexId(':id')
        // return where sql
        sql = `WHERE ${columnSql} = ${placeholder}`
    }
    // and deleted check if d column exists and set in args
    if (defined(this.model.columns.d) && typeof this.args.where.isDeleted === 'boolean') {
        sql += ` AND ${this.alias}.d = ${this.args.where.isDeleted ? 1 : 0}`
    }

    return sql
}