skip to Main Content

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))

2

Answers


  1. Chosen as BEST ANSWER

    figured it out:

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

  2. You can iterate over the cursor directly:

        column_sum = sum(row[0] for row in cursor)
    

    Or you can use one of the various "fetch" methods to access the results and save them to a variable first.

    Your cursor has 3 methods for fetching:

    1. fetchone() returns a single row
    2. fetchmany(n) returns a list of n many rows
    3. fetchall() returns a list of all rows
        results = cursor.fetchall()
        column_sum = sum(row[0] for row in results)
    

    Note that in all cases one row of data is a tuple. This is the case even if you’re only selecting one column (a 1-tuple).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search