loading
V2EX  ›  Python

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

By loading at 2011 年 12 月 6 日 · 5992 次点击
看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具体优势有多少
8 条回复  •  1970-01-01 08:00:00 +08:00
cloud_dai
   1
cloud_dai  
   2011 年 12 月 6 日
你想直接用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
   2
linnchord  
   2011 年 12 月 6 日
你获取到的结果集应该包含列的名称,你可以遍历生成一个dict的列表。SQLAlchemy生成结果你可以简单认为是一个对象列表,上面的row转换为具体的数据表对应定义的对象。
cloud_dai
   3
cloud_dai  
   2011 年 12 月 6 日
至于SQLAlchemy, 它是个好东西!
除非你的SQL写的优化程度超过SQLAlchemy的机制的,
或很小的任务,也没必要另外装个package。

可以看看它的手册
http://www.sqlalchemy.org/docs/
loading
   4
loading  
OP
   2011 年 12 月 6 日
@cloud_dai 感谢,对于SQLAlchemy还是值得学习的,嗯,有空我学习下。
@linnchord 好的,我看看有没包含列名。
SErHo
   5
SErHo  
   2011 年 12 月 6 日
推荐一个非常小巧的ORM,https://github.com/coleifer/peewee
est
   6
est  
   2011 年 12 月 6 日
@cloud_dai 正解。DictCursor
loading
   7
loading  
OP
   2011 年 12 月 7 日
@SErHo 感谢推荐,看起来不错!
现在这个小东东写到一半了,我觉得还是吐血恶心地写完再用吧!还不知道这东西到时用不用呢。。
。
目前任务感觉还是小型的,还凑合。
SErHo
   8
SErHo  
   2011 年 12 月 7 日
@loading 我就是写个小东西,直接用SQL觉得很麻烦,用SQLAlchemy、Storm又感觉太庞大了,于是找到了这个。
推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
© 2026 V2EX · 56ms · 3.9.8.5