Search code examples
pythonmysqlsqlpymysql

How to Append "Decimal" from MySQL query result in Python


I am running a MySql query in Python using the following code:

cur = conn.cursor()
query = ("""select sum(if(grade is not null,1,0)) as `test`,
    sum(if(grade < 7,1,0)) as `bad`,
    sum(if(grade < 7,1,0))/sum(if(grade is not null,1,0))*100 as `Pct Bad Grade`,
    student
    from grades_database
    where test_date >= '2014-08-01'
    group by student
    order by `Pct Bad Grade` desc;""")
cur.execute(query)

and I get a result something like

(Decimal('1'), Decimal('3'), Decimal('50.0000'), 'John Doe')

I need to remove the "Decimal" string in front of the values.

I tried using the following from Past Example

output = []
for row in cur:
    output.append(float(row[0]))
print output

But it gives me this

[20.0, 5.0, 3.0, 7.0, 7.0, 2.0, 6.0, 7.0, 7.0, 7.0,...]

Ideally I would like to rearrange the order of the the output and get something like

(John Doe, 50, 3, 1)]

from

(Decimal('1'), Decimal('3'), Decimal('50.0000'), 'John Doe')

Solution

  • Change the order of your query to get the order you want (name then grades)

    cur = conn.cursor()
    query = ("""select student,
        sum(if(grade is not null,1,0)) as `test`,
        sum(if(grade < 7,1,0)) as `bad`,
        sum(if(grade < 7,1,0))/sum(if(grade is not null,1,0))*100 as `Pct Bad Grade`
        from grades_database
        where test_date >= '2014-08-01'
        group by student
        order by `Pct Bad Grade` desc;""")
    cur.execute(query)
    

    You can then change the values decimal, so skip the first index (the name).

    for index, row in enumerate(cur):
        if index:
            output[index] = int(row)
    print output