将数据从mySQL传递到Flask中的api

问题描述

我需要使用Flask在Python中将数据从MysqL转换为JSON。 我直接在MysqL中使用转换,但它给了我错误。 这是代码

@app.route('/getdata')
def getdata():
    cnx = MysqL.connector.connect(**app.connDBConfig)

    cursor = cnx.cursor()

    query = "SELECT JSON_ARRAYAGG(JSON_OBJECT('nome',columnName,'cognome',columnSur,)) from table;"

    cursor.execute(query)

    data = ""
    for elem in cursor:
        data = elem

    return jsonify(data)

这给了我坚固的JSON

[ “ [{” nome“:” enry“,” cognome“:” ford“},{” nome“:” michel“,” cognome“:” rodriguez“},{” nome“:” paul“,” cognome“ :“ roger”},{“ nome”:“ marcial”,“ cognome”:“ corz”}]“ ]

这是为什么以及如何解决

编辑

如果我使用fethall,它将始终在一个对象中提供所有JSON

解决方法

您应该使用cursor.fetchall()cursor.fetchmany()从游标中获取数据。文档here

光标对象不是数据! ,它只是一个可以帮助您获取数据的处理程序。