Python中让MySQL查询结果返回字典类型的方法

import pymysql
host='localhost'
user='root'
passwd='root'
port=3306
db='test'
db=pymysql.connect(
    host=host,
    user=user,
    passwd=passwd,
    db=db,
    port=port,
    charset='utf8',
    cursorclass = pymysql.cursors.DictCursor
)
cursor=db.cursor()
sql="select * from documents"
try:
    cursor.execute(sql)
    result=cursor.fetchall()
    for i in result:
        for j in i:
            print(j,"=>",i[j])
            print(" ")
except:
    print('error')
db.close()

在默认情况下cursor方法返回的是BaseCursor类型对象,BaseCursor类型对象在执行查询后每条记录的结果以列表(list)表示。如果要返回字典(dict)表示的记录,就要设置cursorclass参数为MySQLdb.cursors.DictCursor类。

posted on 2018-01-15 10:31  weblee  阅读(16430)  评论(0编辑  收藏  举报