mysqldb cursor returning type along with result ?

P

Paul O'Sullivan

Just taken to Python (2.5)and started to look at some DB cursor stuff
using MySQL. Anyway, after creating a query that in MySQL that has a
result set of decimals I find that the cursor in python after a
fetchall() returns a tuple that contains the following ::

((Decimal("101.10"),), (Decimal("99.32"),), (Decimal("97.95"),),
(Decimal("98.45"),), (Decimal("97.39"),), (Decimal("97.91"),), (Decimal
("98.08"),), (Decimal("97.73"),))

as such :
sum(result)
fails with "TypeError: unsupported operand type(s) for +: 'int' and
'tuple'"

How do I either get the resultset back as 'float' or convert the
returned tuple to 'floats'.?

Thanks, Newb.
 
T

Tim Chase

((Decimal("101.10"),), (Decimal("99.32"),), (Decimal("97.95"),),
(Decimal("98.45"),), (Decimal("97.39"),), (Decimal("97.91"),), (Decimal
("98.08"),), (Decimal("97.73"),))

as such :
sum(result)
fails with "TypeError: unsupported operand type(s) for +: 'int' and
'tuple'"

How do I either get the resultset back as 'float' or convert the
returned tuple to 'floats'.?

Well, what you have is a tuple-of-tuples-of-decimals, and Sum can
handle Decimal types just fine. You simply have to extract the
first (only) item in each row:

sum(row[0] for row in result)

or

sum(value for (value,) in result)

whichever makes more sense to you.

-tkc
 
L

Lie Ryan

Just taken to Python (2.5)and started to look at some DB cursor stuff
using MySQL. Anyway, after creating a query that in MySQL that has a
result set of decimals I find that the cursor in python after a
fetchall() returns a tuple that contains the following ::

((Decimal("101.10"),), (Decimal("99.32"),), (Decimal("97.95"),),
(Decimal("98.45"),), (Decimal("97.39"),), (Decimal("97.91"),), (Decimal
("98.08"),), (Decimal("97.73"),))

as such :
sum(result)
fails with "TypeError: unsupported operand type(s) for +: 'int' and
'tuple'"

How do I either get the resultset back as 'float' or convert the
returned tuple to 'floats'.?

I believe it returned decimal.Decimal() objects. You can do arithmetic
with decimal.Decimals, so:

sum(x[0] for x in result)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top