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
kenneth
V2EX  ›  Python

MySQLdb如何按照列名访问结果

  •  
  •   kenneth · 2013-08-20 17:46:06 +08:00 · 4069 次点击
    这是一个创建于 3911 天前的主题,其中的信息可能已经有所发展或是发生改变。
    cursor.execute("select id, name from table")
    rows = cursor.fetchall()
    for row in rows:
    print row.id, row.need_fetch

    AttributeError: 'tuple' object has no attribute 'id'

    求教V2EX高手,如何按照列名来访问不要row[0]这种方式
    5 条回复    1970-01-01 08:00:00 +08:00
    hahastudio
        1
    hahastudio  
       2013-08-20 18:18:33 +08:00
    import MySQLdb
    db = MySQLdb.connect( ... )
    cur = db.cursor(MySQLdb.cursors.DictCursor)
    cur.execute('select * from test;')

    >>> cur.fetchone()
    {'a': 1L, 'c': 3L, 'b': 2L}
    kenneth
        2
    kenneth  
    OP
       2013-08-20 18:28:46 +08:00
    @hahastudio 可能你没理解我的问题
    hahastudio
        3
    hahastudio  
       2013-08-20 19:23:51 +08:00
    @kenneth
    >>> rows = cursor.fetchall()
    >>> for row in rows:
    >>> for row in rows:
    ... print row['a'], row['c']
    ...
    2 3
    2 4
    3 3
    1 2

    都字典了,该怎么按照 column name 访问不是很明确吗,一定要用namedtuple访问的话你构造一个呗= =
    哦,顺带一提,我这列的名字就叫a, b, c= =
    SErHo
        4
    SErHo  
       2013-08-20 19:42:05 +08:00
    lj0014
        5
    lj0014  
       2013-08-21 10:13:52 +08:00
    row = result.fetch_row(how=1)[0]
    row['a']
    row['b']
    ...
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1189 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:49 · PVG 07:49 · LAX 16:49 · JFK 19:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.