I have this code in python:
query = "SELECT product_id FROM product_orders WHERE table_number = "+e
cursor.execute(query)
records = cursor.fetchall()
for record in records:
query2 = "SELECT * FROM productss WHERE id = "+str(record[0])
cursor.execute(query2)
record2 = cursor.fetchall()
sum=0
for record1 in record2:
sum = sum + record1[2]
tree.insert("", tk.END, values=record1)
tree2.insert("", tk.END, values=sum)
The problem is the sum variable does not make summing, but stores only the last value of record1. Any solution for this?
It looks like you have sum = 0 inside of a for loop. Maybe if you take it out of the loop and make it a list of sums that will fix your issue. Also, as another user has said, sum is a built-in name, you can name your variable s instead.
Related
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))
figured it out:
sum = 0
for price in cursor:
sum = sum + price[0]
print(sum)
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:
fetchone() returns a single row
fetchmany(n) returns a list of n many rows
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).
I'm trying to save a column value into a python variable; I query my DB for a int in a columns called id_mType and id_meter depending of a value that I get from a XML. To test it I do the next (I'm new using databases):
m = 'R1'
id_cont1 = 'LGZ0019800712'
xdb = cursor.execute("SELECT id_mType FROM mType WHERE m_symbol = %s", m)
xdb1 = cursor.execute("select id_meter from meter where nombre = %s",
id_cont1)
print (xdb)
print (xdb1)
I get every time the value "1" where the id_mType for 'R1' = 3 and id_meter= 7 for id_cont1 value. I need this to insert in another table (where there are both FK: id_meter and id_mType. Dont know if there is an easiest way)
You can store it in a list. Is that okay?
results=cursor.fetchall()
my_list=[]
for result in results:
my_list.append(result[0])
Now my_list should hold the SQL column you get returned with your query.
Use the fetchone() method to fetch a row from a cursor.
row = xdb.fetchone()
if row:
mtype = row[0]
row = xdb1.fetchone()
if row:
meter = row[0]
I got this code:
cursor.execute('SELECT nom FROM productes WHERE listacompra = 1')
rows = cursor.fetchall()
for row in rows:
print(row[0])
I'd like to have whatever it returns into some variables. How could I do it?
EDIT:
I think I'm not explaining myself properly. What I want is to have two variables with two values of the same column, not of the same row. For example:
There's two rows:
id 1, nom Natillas, listacompra 1
id 2, nom Chocolate, listacompra 1
I'd like to have two (or more) variables in order to have one variable with "Natillas" and other one with "Chocolate".
Thanks
Using list comprehensions:
cursor.execute('SELECT nom FROM productes WHERE listacompra = 1')
rows = cursor.fetchall()
var1 = row[0][0] # or row['nom'] if you are fetching as dict
var2 = row[1][0]
Obviously for this to work you have to be sure query will return at least two rows.
Old answer
The iterator will return a tuple representing the row specified in the query. For example, for the query SELECT id, password FROM users the variable row will contain the id value in the first position and password in the second.
For example:
for row in rows:
id = row[0]
pwd = row[1]
Or, more coincise:
for row in rows:
id, pwd = row
Unless you specify the option cursorclass=pymysql.cursors.DictCursor when defining the connection, in this case it will return a dictionary:
for row in rows:
id = row['id']
pwd = row['password']
rows = cursor.fetchall()
for row in rows:
print(row['<key of table field>'])
i want to use python to populate a database. I have to get values out of a table, calculate a score and fill this score into anoter table. I cant figure out how i can compare the column names of a row from a resultset. Because i dont need all of the columns to calculate, but need a few others as id and type_name for none calculation. So basically i want to do this:
cur = connection.cursor()
QUERY ="SELECT * FROM table"
cur.execute(QUERY)
rs = cur.fetchall()
for row in rs:
for col in row:
// if(col = "X" or col = "Y" or col = "Z"):
calc ...
// else:
use id, type_name whatever ...
how can achieve something like this? Else the code would just blow up like a bomb.
Maybe someone is searching for the answer too. With help of the previous comment, i could solve it like that
field_names = cur.description
for row in rs:
for index, col in enumerate(row):
name = field_names[index][0]
if(name == "..."):
...
elif(name == "..."):
...
I'm generating N random numbers between 0-100. N relies on the amount of rows there is in table_1. There's 200 rows. I get 200 random numbers in a list returned.
I'm trying to insert these 200 numbers from the list as individual rows into table_2's random_number column. There is no link between the random numbers and the 3 other columns in table_2.
r = [random.randint(0,100) for rows in cursor.execute('SELECT * FROM table_1')]
for r in rows:
cursor.execute('UPDATE table_2 SET random_number = (?)', r)
This is what I currently have. I get a
ProgrammingError: Incorrect number of bindings supplied. The current
statement uses 1, and there are 4 supplied
error. I've seen other solutions where they ad (?, ) but it doesnt work. I've also tried:
r = [random.randint(0,100) for rows in cursor.execute('SELECT * FROM table_1')]
r = str(r)
cursor.execute('INSERT INTO table_2 (random_number) VALUES (?)', [','.join(r)])
Which is running, but nothing is being inserted into the random_number column.
I think the problem is that rows is no longer in scope when you access it in your for loop, nor is it the list you'd want to iterate over.
If i understood correctly then you should change your script into something like this:
# generate random list
r_list = [random.randint(0,100) for rows in cursor.execute('SELECT * FROM table_1')]
# iterate over that list and insert
for r in r_list:
cursor.execute('INSERT INTO table_2 (random_number) VALUES (?)', r)
I've resolved my issue. I noticed that it was splitting and saving integers to new rows on their own.
This is how I resolved it:
rows = cursor.execute('SELECT * FROM table_1').fetchall()
r_list = [random.randint(0,100) for row in rows]
for i in xrange(0,len(rows)):
cursor.execute('UPDATE table_2 SET random_number=' + str(r_list[i]) + ' WHERE row_id = ' + str(rows[i][0]))