Python Peewee execute_sql() example
我正在使用Peewee模块作为我的项目的ORM。
我看了整个文件,没有清楚关于如何处理db.execute_sql()的结果的示例。
我跟踪代码,只能找到db.execute_sql()返回光标。
是否有人知道如何处理光标,例如迭代光标并获取返回复杂select语句的结果。
更新:我刚从peewee文件夹中找到了以下源代码,应该会有所帮助我来解决这个问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 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对其进行迭代:
1 2 3 4 5 6 7 | 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] |
文件: