您的位置:首页 > 编程语言 > Python开发

【原創】python sqlite3&nbsp…

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

11.13.4. Row Objects

class sqlite3.RowRow instanceserves as a highly optimized row_factory for Connection objects.It tries to mimic a tuple in most of its features.Itsupports mapping access by column name and index, iteration,representation, equality testing and len().Iftwo Row objectshave exactly the same columns and their members are equal, theycompare equal.Changedin version 2.6: Added iteration andequality (hashability).keys()Thismethod returns a list of column names. Immediately after a query,it is the first member of each tuple in Cursor.description.New inversion 2.6.Let’s assume we initialize a table as in the example givenabove:
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-05BUYRHAT100.035.14
-那其实我们可以看到,用法就是用自定义的一个Row类,其实这个类可以自己写的、Row源码如下:
    """ Returns the keys of the row. """
    pass
    """ x.__eq__(y) <==> x==y """
    pass
    """ x.__getitem__(y) <==> x[y] """
    pass
    """ x.__ge__(y) <==> x>=y """
    pass
    """ x.__gt__(y) <==> x>y """
    pass
    """ x.__hash__() <==> hash(x) """
    pass
    pass
    """ x.__iter__() <==> iter(x) """
    pass
    """ x.__len__() <==> len(x) """
    pass
    """ x.__le__(y) <==> x<=y """
    pass
    """ x.__lt__(y) <==> x
    pass
    """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
    pass
    """ x.__ne__(y) <==> x!=y """
        pass
如果我们自己写,应该怎么写呢,下面是我自己写的一小段,init第一个参数应当为Cursor类,这里写一个none就可以了。
    super(TaskEntity, self).__init__(=id, name=name)
    value = super(TaskEntity, self).__getitem__(item)
    if value:
        return value[0]
    else:
        return default
    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].namezhang>>> print rows[0]["name"]zhang
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: