Python Peewee execute

编程入门 行业动态 更新时间:2024-10-27 06:34:18
本文介绍了Python Peewee execute_sql()示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我将Peewee模块用作项目的ORM。

I am using the Peewee module as the ORM for my project.

我已经阅读了整个文档,没有清晰的示例如何处理db.execute_sql()的结果。

I read the entire documentation, there is no clear example on how to process the result from db.execute_sql().

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

I traced the code, only can find db.execute_sql() return back the cursor.

是否有人知道如何处理游标,例如对其进行迭代并从复杂的select语句获取的结果。

Does anyone knows how to process the cursor, such as iterate over it and get back the result from complex select statement.

更新:我刚刚从peewee文件夹中找到了以下源代码,它应该有助于我解决此问题。

Update: I just found the following source code from peewee folder, it should help me to resolve this problem.

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对其进行迭代:

Peewee returns a cursor. Then you can use the db-api 2 to iterate over it:

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

本文发布于:2023-10-24 07:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523342.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Python   Peewee   execute

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!