【原創】python sqlite3&nbsp…
2017-03-20 14:47
225 查看
sqllite3默認查詢到的結果是list[tuple(value, value...)]找了半天,也沒有發現類似Mysqldb 的DictCursor,最後在官方網站看到說明
11.13.4. Row Objects
class sqlite3.RowA Row 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
相关文章推荐
- 【原】Python3 下 MP3格式文件的ID…
- python 生成验证码
- android&nbsp;SQLite&nbsp;-&nbsp;close()&nbsp;was&nbsp;nev…
- python学习&nbsp;import
- 内部赛3 F Frequent values
- 内部赛 3 D Deli Deli
- 'sqlite3' isn't an available database backend.
- 关于ActivePython&nbsp;无法正常运行的…
- dive&nbsp;into&nbsp;python&nbsp;第&nbsp;5&nbsp;章&nbsp;对象和…
- 以后不看DIVE&nbsp;INTO&nbsp;PYTHON了,对PY…
- Python&nbsp;学习积累《一》
- android&nbsp;sqlite&nbsp;增删改[insert、up…
- 《dinv&nbsp;into&nbsp;python》开始了解pyth…
- Dive&nbsp;into&nbsp;python&nbsp;第4章&nbsp;自省的威…
- python&nbsp;中用SWIG包装C和C++和接口…
- [转]Python实例讲解 -- wxpython …
- 3&nbsp;Nginx的基本配置和优化
- Coding&nbsp;Python&nbsp;GNU&nbsp;Radio&nbsp;Applicat…
- Python&nbsp;DOCStrings示例程序
- Django(迪亚戈)--Python&nbsp;Web&nbsp;框…