gpt4 book ai didi

Python Peewee execute_sql() 示例

转载 作者:太空狗 更新时间:2023-10-29 18:17:20 25 4
gpt4 key购买 nike

我正在使用 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

最佳答案

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])

文档:Database.execute_sql

关于Python Peewee execute_sql() 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18500956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com