Python Peewee execute_sql()示例

use*_*968 12 python sql database peewee

我使用Peewee模块作为我项目的ORM.

我阅读了整个文档,没有关于如何处理db.execute_sql()的结果的明确示例.

我跟踪了代码,只能找到db.execute_sql()返回光标.

有谁知道如何处理游标,例如迭代它并从复杂的select语句中获取结果.

更新:我刚从peewee文件夹中找到以下源代码,它应该可以帮我解决这个问题.

class QueryResultWrapper(object):
    """
    Provides an iterator over the results of a raw Query, additionally doing
    two things:
    - converts rows from the database into python representations
    - ensures that multiple iterations do not result in multiple queries
    """
    def __init__(self, model, cursor, meta=None):
        self.model = model
        self.cursor = cursor

        self.__ct = 0
        self.__idx = 0

        self._result_cache = []
        self._populated = False
        self._initialized = False

        if meta is not None:
            self.column_meta, self.join_meta = meta
        else:
            self.column_meta = self.join_meta = None

    def __iter__(self):
        self.__idx = 0

        if not self._populated:
            return self
        else:
            return iter(self._result_cache)

    def process_row(self, row):
        return row

    def iterate(self):
        row = self.cursor.fetchone()
        if not row:
            self._populated = True
            raise StopIteration
        elif not self._initialized:
            self.initialize(self.cursor.description)
            self._initialized = True
        return self.process_row(row)

    def iterator(self):
        while True:
            yield self.iterate()

    def next(self):
        if self.__idx  self.__ct):
            try:
                self.next()
            except StopIteration:
                break

col*_*fer 25

Peewee返回一个光标.然后你可以使用db-api 2迭代它:

cursor = db.execute_sql('select * from tweets;')
for row in cursor.fetchall():
    print row

cursor = db.execute_sql('select count(*) from tweets;')
res = cursor.fetchone()
print 'Total: ', res[0]
Run Code Online (Sandbox Code Playgroud)

  • 是否有一个fetch返回一个映射列名称的字典? (4认同)
  • @KJW尝试使用`cursor.description`来获取列名称:`col_names = [col[0] for col incursor.description] res = [dict(zip(col_names, row)) for row incursor.fetchall( )]` (2认同)