python MySQLdb结果转换成字典

使用字典 Cursor

import MySQLdb as mdb

con = mdb.connect('localhost', 'root', '******', 'test')

def test_dict_cursor():
    with con:
        cur = con.cursor(mdb.cursors.DictCursor) # 字典 cursor
        cur.execute('select * from writers limit 4')

        # rows 为字典的元组
        rows = cur.fetchall()
        for row in rows:
            print row['id'], row['name'] # 通过列名访问结果

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This blog is kept spam free by WP-SpamFree.