get raw decimal value from mysqldb query

泄露秘密 提交于 2019-11-26 16:59:30

问题


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!


回答1:


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



回答2:


Use float():

output.append(float(row[4]))

But float() can result in something like:

In [184]: float(Decimal('10.02'))
Out[184]: 10.02

In [185]: float(Decimal('20.24'))
Out[185]: 20.239999999999998



回答3:


If you are trying to write a generic code that operates on the column output, the above solution won't workout. In that case we can write our SELECT query in a way that the column in returned as String and we just get the value of what we want. The query can be framed in below way,

SELECT 
 CAST(COL1 AS CHAR) AS COL1,
 CAST(COL2 AS CHAR) AS COL2,
 .
 .
 .
FROM TABLE;



回答4:


from decimal import Decimal
c=db.cursor()
c.execute("""select * from table""")
output = []
for row in c:
    row_data = []
    for data in row:
        if type(data) is Decimal:
            row_data.append(float(data))
        else:
            row_data.append(str(dat))
        output.append(row_data)

;)



来源:https://stackoverflow.com/questions/12661999/get-raw-decimal-value-from-mysqldb-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!