Home > database >  psycopg2 - sum of prices
psycopg2 - sum of prices

Time:10-29

I seem to have relatively easy question, but I have a little problem. I would like to iterr through the column prices in table products and then sum the prices. I know an easy solution would be to change sql query -> sum(price), but in my exercise I need to avoid this solution.

import psycopg2

connection = psycopg2.connect(
    host='host',
    user='user', 
    password='password',  
    dbname='dbname', 
)

cursor = connection.cursor()
sql = "select price from products"
cursor.execute(sql)

for price in cursor:
    print(sum(price))

CodePudding user response:

You're trying to access the results by iterating over the cursor itself. You're missing a step. You first need to "fetch" the results and save them to a variable. Once you've fetched, then you can sum them.

Your cursor has 3 methods for fetching:

  • fetchone() returns a single row
  • fetchmany(n) returns a list of n many rows
  • fetchall() returns a list of all rows

In each case, one row of data is a tuple. I think this is the case even if you're only selecting one column (a 1-tuple).

CodePudding user response:

figured it out:

sum = 0
for price in cursor:
    sum = sum   price[0]
print(sum)
  • Related