Python将Mysqldb中cursor.fetchall()的结果读取为JSON

1.定义函数如下


def fetch_dict_result(cur):
    row_headers=[x[0] for x in cur.description] #this will extract row headers
    rv = cur.fetchall()
    json_data=[]
    for result in rv:
            json_data.append(dict(zip(row_headers,result)))
    return json.dumps(json_data)

2.调用

cursor.execute("select * from test")

json=fetch_dict_result(cursor)

print(json)

 

你可能感兴趣的:(Python,python,json,mysql)