如何在Python中从MySQL查询结果中附加“Decimal”

时间:2014-10-10 16:38:22

标签: python mysql sql pymysql

我使用以下代码在Python中运行MySql查询:

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)

我得到了类似

的结果
(Decimal('1'), Decimal('3'), Decimal('50.0000'), 'John Doe')

我需要删除值前面的“Decimal”字符串。

我尝试使用Past Example

中的以下内容
output = []
for row in cur:
    output.append(float(row[0]))
print output

但它给了我这个

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

理想情况下,我想重新排列输出的顺序,并获得类似

的内容
(John Doe, 50, 3, 1)]

来自

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

1 个答案:

答案 0 :(得分:1)

更改查询的顺序以获得所需的订单(名称然后成绩)

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)

然后您可以更改十进制值,因此请跳过第一个索引(名称)。

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