Search code examples
pythonmysqlflaskmysql-connector-python

convert mysql query return type


I am developing a webapp for a school project in Flask. I am very new to python and flask.

In function "get_absence" i am executing a mysql query and i get result. (The query is working in mysql command line and giving output 15) But my result on the html page is in the form "(Decimal('15'),)". I want to extract out the number, so that i can display only 15 on the web. How can i do that?

The result from the query goes from get_absence to API function get_info and then sent to the html page "page.html". It displays on the page as "(Decimal('15'),)".

I cannot convert from tuples to integer. Anyone?

util.py:

def get_absence(database):
    try:
        days = []
        cur = database.cursor()
        cur.execute(queries["select SUM(dates) FROM leaves WHERE 
                            emp_id = 14"]) 
        for a in cur:
            num = a; 
        return a
    except:
        return jsonify("Internal server error"), 500
    finally:
        cur.close()

FLASK app.py:

@app.route("/get_info/", methods=["GET"])
def get_info():
    db = get_db()
    cur = db.cursor(buffered=True)
    try: 
        days = get_absence(get_db() )  
        return render_template("page.html", days=days)  
    except mysql.connector.Error as err:
        return render_template("error.html", err = err)
    finally:
        cur.close()

HTML:

<h1>"{{ days }}" </h1>

When rendered, broswer shows: "(Decimal('15'),)"


Solution

  • The execute method will always return a iterator where each element is a tuple that represent a row with multiples columns.

    Then in your case you just take the first element from "days" tumple:

    days[0]
    

    Then you will have a decimal object. You can round it in a integer doing:

    int(days[0])
    

    Also, if you are expecting a single element, then you can use cursor.fetchone() in order to avoid the for loop over cur object.

    You can read more info here