sqllite3默認查詢到的結果是list[tuple(value, value...)]
找了半天,也沒有發現類似Mysqldb 的DictCursor,最後在官方網站看到說明

11.13.4. Row Objects

class  sqlite3. Row

Row instance serves as a highly optimized row_factory for Connection objects. It tries to mimic a tuple in most of its features.

It supports mapping access by column name and index, iteration, representation, equality testing and len().

If two Row objects have exactly the same columns and their members are equal, they compare equal.

Changed in version 2.6: Added iteration and equality (hashability).

keys ( )

This method returns a list of column names. Immediately after a query, it is the first member of each tuple in Cursor.description.

New in version 2.6.

Let’s assume we initialize a table as in the example given above:

conn = sqlite3.connect(":memory:"
c = conn.cursor() 
c.execute('''create table stocks
(date text, trans text, symbol text,
 qty real, price real)'''
c.execute("""insert into stocks
          values ('2006-01-05','BUY','RHAT',100,35.14)"""
conn.commit()
c.close()

Now we plug Row in:

>>>
>>> conn.row_factory = sqlite3.Row 
>>> c = conn.cursor() 
>>> c.execute('select * from stocks')
 
>>> r = c.fetchone() 
>>> type(r)
 
>>> r
(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14) 
>>> len(r)
5 
>>> r[2]
u'RHAT' 
>>> r.keys()
['date', 'trans', 'symbol', 'qty', 'price'] 
>>> r['qty']
100.0 
>>> for member in r: print member,

2006-01-05
BUY
RHAT
100.0
35.14
-
那其实我们可以看到,用法就是用自定义的一个Row类,其实这个类可以自己写的、
Row源码如下:
class Row(object):
    # no doc
    def keys(self, *args, **kwargs): # real signature unknown
    
    """ Returns the keys of the row. """
        pass
    def __eq__(self, y): # real signature unknown; restored from __doc__
    
    """ x.__eq__(y) <==> x==y """
        pass
    def __getitem__(self, y): # real signature unknown; restored from __doc__
    
    """ x.__getitem__(y) <==> x[y] """
        pass
    def __ge__(self, y): # real signature unknown; restored from __doc__
    
    """ x.__ge__(y) <==> x>=y """
        pass
    def __gt__(self, y): # real signature unknown; restored from __doc__
    
    """ x.__gt__(y) <==> x>y """
        pass
    def __hash__(self): # real signature unknown; restored from __doc__
    
    """ x.__hash__() <==> hash(x) """
        pass
    def __init__(self, *args, **kwargs): # real signature unknown
    
    pass
    def __iter__(self): # real signature unknown; restored from __doc__
    
    """ x.__iter__() <==> iter(x) """
        pass
    def __len__(self): # real signature unknown; restored from __doc__
    
    """ x.__len__() <==> len(x) """
        pass
    def __le__(self, y): # real signature unknown; restored from __doc__
    
    """ x.__le__(y) <==> x<=y """
        pass
    def __lt__(self, y): # real signature unknown; restored from __doc__
    
    """ x.__lt__(y) <==> x
        pass
    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
    
    """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass
    def __ne__(self, y): # real signature unknown; restored from __doc__
    
    """ x.__ne__(y) <==> x!=y """
        pass
如果我们自己写,应该怎么写呢,下面是我自己写的一小段,init第一个参数应当为Cursor类,这里写一个none就可以了。


class UserEntity(dict):
    # todo: 需要跟数据库列完全对应 ..
    def __init__(self, none=None, name=None, id=None):
    
    super(TaskEntity, self).__init__(id=id, name=name)

  
    def get(self, k, d=None):
        return self.__getitem__(k, d)

    def __getitem__(self, item, default=None):
    
    value = super(TaskEntity, self).__getitem__(item)
            if value:
                    return value[0]
            else:
                    return default
    @property
    def id(self):
        return self.get("id")

    @id.setter
    def id(self, id):
    
    self["id"] = id
测试一下:
>>> from User_entity import UserEntity as user
>>> import sqlite3 as sql
>>> conn = sql.connect("my.db")
>>> conn.row_factory =  user
>>> cur = conn.cursor()
>>> ex = cur.execute("select * from users")
>>> rows = ex.fetchall()
>>> rows
[{'name': (u'zhang',), 'id': None,'age': None}]
>>> print rows[0].name
zhang
>>> print rows[0]["name"]
zhang

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐