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
figured it out:
You can iterate over the cursor directly:
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:
fetchone()
returns a single rowfetchmany(n)
returns a list of n many rowsfetchall()
returns a list of all rowsNote 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).