简体   繁体   中英

Retrieve value from a fetchone() call in python 3

I am fairly new to python and I can not find the answer to my question anywhere. Unless I just don't understand the answers given. I have a database cursor and I execute this command:

cmd = 'select value from measurement where measurement_location is ?'
crs.execute(cmd, [location_id])
print(crs.fetchone())

Which prints:

{'value': 73.97486139568466}

I need to use the float 73.97.... in some calculations to compute an average. My problem is that I can't figure out how to pull the float from the fetchone() return.

fetchone is returning you a dictionary for each row mapping the field name in the result (only value in this example) with the value for that row. To use it you can do

cmd = 'select value from measurement where measurement_location is ?'
crs.execute(cmd, [location_id])
row = crs.fetchone()
print(row['value'])

print(row['value'] * 100)

or whatever other things you want to do with that result

You can do something like below:

row=crs.fetchone()

for x in row:

    print(x)

Value=x

you can use value variable in your calculations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM