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]))
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 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.
I am using sqlite3 in python 3 I want to get only the updated data from the database. what I mean by that can be explained as follows: the database already has 2 rows of data and I add 2 more rows of data. How can I read only the updated rows instead of total rows
Note: indexing may not help here because the no of rows updating will change.
def read_all():
cur = con.cursor()
cur.execute("SELECT * FROM CVT")
rows = cur.fetchall()
# print(rows[-1])
assert cur.rowcount == len(rows)
lastrowids = range(cur.lastrowid - cur.rowcount + 1, cur.lastrowid + 1)
print(lastrowids)
If you insert rows "one by one" like that
cursor.execute('INSERT INTO foo (xxxx) VALUES (xxxx)')
You then can retrieve the last inserted rows id :
last_inserted_id = cursor.lastrowid
BUT it will work ONLY if you insert a single row with execute. It will return None if you try to use it after a executemany.
If you are trying to get multiple ids of rows that were inserted at the same time see that answer that may help you.
I have a SQL Server database that has a table that lists other tables along with some meta data on them. I can pull this out through Python into a List. What I want to do then though is query each table for the number of rows in it and then append the result into my list.
So for example, I run the first part of the script and I get a List of items, each one containing a list of 3 items (name,activity, Table Name). I then want to cycle through my list, pick up the third item, use it in my SQL query and then append the result into a 4th item in the list.
It starts off
[[table1, act1, Table_1],[table2, act2, Table_2],[table3, act3, Table_3]]
The second part, first takes Table_1, counts the rows and then appends it the list
[[table1, act1, Table_1,10],[table2, act2, Table_2],[table3, act3, Table_3]]
and then for list 2 etc
[[table1, act1, Table_1,10],[table2, act2, Table_2,16],[table3, act3, Table_3]]
Tried a few things but not got any further!
Thanks in advance.
import pyodbc
conn = pyodbc.connect(connetStr)
cursor = conn.cursor()
wffList=[]
cursor.execute('SELECT C_NAME,C_ACTIVE, C_TABLE_NAME from T_FORM_HEAD')
for row in cursor:
wffList.append(row)
for row in wffList:
tabName=row[2]
quer=('SELECT Count(*) FROM '+ tabName)
cursor.execute(quer)
rowCount=cursor.fetchone()
You can creat new list and append row with all four values
new_results = []
for row in wffList:
tabName = row[2]
quer = ('SELECT Count(*) FROM '+ tabName)
cursor.execute(quer)
rowCount = cursor.fetchone()
row.append(rowCount)
new_results.append(row)
print(new_results)
Or you can use enumerate to get row's number
for number, row in enumerate(wffList):
tabName = row[2]
quer = ('SELECT Count(*) FROM '+ tabName)
cursor.execute(quer)
rowCount = cursor.fetchone()
wffList[number].append(rowCount)
print(wfflist)
But probably you could also write one SQL query to get all at once.
But it could be to complex for me at this moment.
I am trying to increment row in MySQL database like this
rows = cursor.fetchall()
i = 0
for row in rows:
cursor.execute("UPDATE Table SET order = %s WHERE name = 'JAMES'", (i,))
db.commit()
i += 1
But at the end order for all of the items is 19, and the length of rows is 20. How can I have it go form 0 to 19, I though if I commit() after each loop this would be solved?
Thanks
Maybe you meant something like this (WHERE clause change for rows):
rows = cursor.fetchall()
for i, row in enumerate(rows):
cursor.execute("UPDATE Table SET order = %s WHERE name = %s", (i, row.name))
db.commit()
Otherwise, order fields or one record is updated multiple times.