Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

python - get raw decimal value from mysqldb query

I am executing a mysql query in python using the MySQLdb package. The code looks something like this:

c=db.cursor()
c.execute("""select * from table""")
output = []
for row in c:
    output.append(row[4])

where row[4] contains a decimal value that I want to store in the output list.

The problem is every value that I am getting looks like this: Decimal('XX.XX') where all I want in the output list is XX.XX. At the end of the script, my output list looks like this:

[Decimal('10.02'), Decimal('20.24'), ...]

But I need it to just contain the numbers, like this:

[10.02, 20.24, ...]

How do I do that?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can either convert a Decimal object to a string:

cursor = db.cursor()
cursor.execute("""select * from table""")
output = []
for row in cursor:
    output.append(str(row[4]))

Or to a float:

cursor = db.cursor()
cursor.execute("""select * from table""")
output = []
for row in cursor:
    output.append(float(row[4]))

Converting it to a float will cause it to lose its full precision, so a value like 20.24 will become 20.239999999999998.

Also, casting it to a float will raise an Exception if the value is None. To avoid that, you can use a helper function like this:

def convert_mysql_decimal_to_float(decimal_object):
    if (decimal_object == None):
        return None
    else:
        return float(decimal_object)

cell_value = convert_mysql_decimal_to_float(row[4])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...