1

'm fetching some data from MySQL database using:

cur.execute("SELECT memory FROM vm WHERE hv_id=5")
for row in cur.fetchall() :
print row[0]

This prints something like this:

512
1024
4096
4096
2048
4096
1024
6144
1024
1024
4096

I need sum the above and set it as a variable for further calculations.

2 Answers 2

7

Why don't use SUM() in the query itself:

cur.execute("SELECT SUM(memory) FROM vm WHERE hv_id=5")
result = cur.fetchone()[0]
Sign up to request clarification or add additional context in comments.

Comments

0

another answer if you are finding something Pythonista

cur.execute("SELECT memory FROM vm WHERE hv_id=5")
result = sum(int(x) for x in cur.fetchall())
print result 

or

result = sum(map(int, cur.fetchall()))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.