Pauly
Pauly

Reputation: 101

python mysqldb single row/column returned tuple value

db_quote_cursor.execute("""select lastince 
                           from `here` 
                           order by `date` desc, `time` desc 
                           limit 1""")
thisout= db_quote_cursor.fetchone()

thisout is a single value that is a float. I need to do calculations on it but can't cast it as a float in the tuple.

!work(pleasework=float(thisout[0]))

I tried converting it to a list, that didn't work either. How do I directly access the value within the tuple when I don't want/need to loop through it? Or something else maybe...

Here's what I get back from the database:

print(this out)
# -> ((Decimal('118'),),) 

And this is the error I'm getting:

>>> result = float(thisout[0]) 
Traceback (most recent call last): File "file.1.py", line 56, in <module> 
TypeError: float() argument must be a string or a number 

Upvotes: 0

Views: 1124

Answers (2)

mechanical_meat
mechanical_meat

Reputation: 169304

The situation is more clear now that you posted the traceback. Thank you.

You're getting back a Decimal object.
This is just as good, in fact, better than a float.

You needn't convert it, and may simply begin your calculations:

thisout[0] += 1 # works fine

However, note that you cannot do:

thisout[0] += 1.0 # this is a TypeError

In the above case you would do instead:

import decimal as dc
thisout[0] += dc.Decimal('1.0')

Upvotes: 1

Collin Green
Collin Green

Reputation: 2196

If the result is simply a 1-tuple, you can access it as bernie says (and your code apparently tries) with thisout[0]. I'm guessing you're having a different error when trying to parse the float; post the stacktrace or the exception.

Upvotes: 0

Related Questions