2013-08-29 62 views
6

Tôi đang sử dụng mô-đun Peewee làm ORM cho dự án của mình.Python Peewee execute_sql() ví dụ

Tôi đã đọc toàn bộ tài liệu, không có ví dụ rõ ràng về về cách xử lý kết quả từ db.execute_sql().

Tôi đã truy tìm mã, chỉ có thể tìm thấy db.execute_sql() trả lại con trỏ.

Có ai biết cách xử lý con trỏ, chẳng hạn như lặp lại trên con trỏ và nhận được trả lại kết quả từ câu lệnh chọn phức tạp.

Cập nhật: Tôi vừa tìm thấy mã nguồn sau đây từ thư mục peewee, nó sẽ giúp tôi giải quyết vấn đề này.

 
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 
+0

Loại đối tượng được trả về là gì? Chạy 'sql_execute()' và in kết quả để xem loại của nó. – xbonez

Trả lời

16

Peewee trả về con trỏ. Sau đó, bạn có thể sử dụng db-api 2 để lặp qua nó:

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] 
+2

có tìm nạp trả về từ điển bản đồ tên cột không? – KJW

+2

@KJW http://docs.peewee-orm.com/en/latest/peewee/api.html#RawQuery –