简体   繁体   中英

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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM