如何将方便地把select得出的数据变为字典

2011-12-06 09:11:51 +08:00
 loading
看flask的例子,从数据库获得数据是这样写的
cur = g.db.execute('''select a,b,c from user ''',[session['user_id']])
members = [dict(a=row[0], b=row[1],
c=row[2]) for row in cur.fetchall()]
感觉这样写row[*]好烦,能不能直接将列名写到字典里呢?
select * 并不这么影响的,感觉写起来很烦。
我目前只会直接写SQL语句,还没用到SQLAlchemy,SQLAlchemy具体优势有多少
4959 次点击
所在节点    Python
8 条回复
cloud_dai
2011-12-06 09:43:26 +08:00
你想直接用MySQLdb?


import MySQLdb
import MySQLdb.cursors

db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', db = 'test',cursorclass = MySQLdb.cursors.DictCursor)

cursor = db.cursor()
cursor.execute('select * from user')
rs = cursor.fetchall()

#结果
# ({'name': "cloud", 'cash': 1000L}, {'name': "luce", 'cash': 2000L}, ...)

#也可以这样
db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', db = 'test')
cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)

#具体的指南
http://mysql-python.sourceforge.net/MySQLdb.html
linnchord
2011-12-06 09:45:46 +08:00
你获取到的结果集应该包含列的名称,你可以遍历生成一个dict的列表。SQLAlchemy生成结果你可以简单认为是一个对象列表,上面的row转换为具体的数据表对应定义的对象。
cloud_dai
2011-12-06 09:53:27 +08:00
至于SQLAlchemy, 它是个好东西!
除非你的SQL写的优化程度超过SQLAlchemy的机制的,
或很小的任务,也没必要另外装个package。

可以看看它的手册
http://www.sqlalchemy.org/docs/
loading
2011-12-06 10:30:35 +08:00
@cloud_dai 感谢,对于SQLAlchemy还是值得学习的,嗯,有空我学习下。
@linnchord 好的,我看看有没包含列名。
SErHo
2011-12-06 11:25:22 +08:00
推荐一个非常小巧的ORM,https://github.com/coleifer/peewee
est
2011-12-06 11:48:17 +08:00
@cloud_dai 正解。DictCursor
loading
2011-12-07 16:45:09 +08:00
@SErHo 感谢推荐,看起来不错!
现在这个小东东写到一半了,我觉得还是吐血恶心地写完再用吧!还不知道这东西到时用不用呢。。

目前任务感觉还是小型的,还凑合。
SErHo
2011-12-07 17:55:39 +08:00
@loading 我就是写个小东西,直接用SQL觉得很麻烦,用SQLAlchemy、Storm又感觉太庞大了,于是找到了这个。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/22909

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX