V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
loading
V2EX  ›  Python

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

  •  
  •   loading ·
    ycf · 2011-12-06 09:11:51 +08:00 · 4936 次点击
    这是一个创建于 4549 天前的主题,其中的信息可能已经有所发展或是发生改变。
    看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-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
        2
    linnchord  
       2011-12-06 09:45:46 +08:00
    你获取到的结果集应该包含列的名称,你可以遍历生成一个dict的列表。SQLAlchemy生成结果你可以简单认为是一个对象列表,上面的row转换为具体的数据表对应定义的对象。
    cloud_dai
        3
    cloud_dai  
       2011-12-06 09:53:27 +08:00
    至于SQLAlchemy, 它是个好东西!
    除非你的SQL写的优化程度超过SQLAlchemy的机制的,
    或很小的任务,也没必要另外装个package。

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

    目前任务感觉还是小型的,还凑合。
    SErHo
        8
    SErHo  
       2011-12-07 17:55:39 +08:00
    @loading 我就是写个小东西,直接用SQL觉得很麻烦,用SQLAlchemy、Storm又感觉太庞大了,于是找到了这个。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   4909 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 03:50 · PVG 11:50 · LAX 20:50 · JFK 23:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.