pythonmysqlfetchall

Python mysql fetchall() returns additional characters


I am trying to retrieve values from a table to use in a calculation. The code below

mycursor = mydb.cursor()

mycursor.execute("SELECT number FROM info")

rows = mycursor.fetchall()

print (rows)

This returns this list

[(Decimal('30.00'),), (Decimal('66.00'),), (Decimal('72.00'),)]

How can I retrieve the numerical value only either in a list or tuple like

[30.00, 66.00, 72.00]

Solution

  • The original data type in mydb might be a Decimal object. So you can cast the datatype in the MySQL query or python code.

    1) Case in MySQL:

    SELECT CAST(number AS DOUBLE) FROM info
    

    but this code returns the fetched rows as [(30.00,), (66.00,), (72.00,)] because the tuples represent the columns of the query result.

    2) Case in python code:

    converted_rows = list(map(lambda row:float(row[0]), rows))
    

    It will return [30.00, 66.00, 72.00] list.