python操作mysql返回结果是字典

import pymysql
host='localhost'
user='root'
passwd='123456'
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类。

猜你喜欢

转载自blog.csdn.net/weixin_42341608/article/details/81389459
今日推荐