Increment row MySql Python - python

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.

Related

can I get only the updated data from database instead of all the data

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.

Error involving SQLite 3 prevents me from adding to database properly

I've been working most of today on a function that creates a record in an sqlite table. I believe I am finally making some progress and it currently looks like this:
shopping = True
while shopping:
itemToAdd = input("Please enter the ID of the item to add to the basket: ")
basket.append(itemToAdd)
print(basket)
continueShop = input("Continue shopping?(y/n): ")
if continueShop == "n":
conn.execute("INSERT INTO Orders (UserID) VALUES (?)", (results[0][0],))
lastID = conn.execute("SELECT last_insert_rowid()")
conn.commit()
counter = 0
for items in basket:
createOrderItems = "INSERT INTO OrderItems (OrderID, ProductID) VALUES (?,?)"
conn.execute(createOrderItems, (lastID, basket[counter]))
counter = +1
conn.commit()
However, I am now encountering this error to do with lastID if I am reading the error correctly.
line 107, in
conn.execute(createOrderItems, (lastID, basket[counter])) sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
I have 2 tables that I am currently attempting to use:
Orders - contains only an orderID and userID
OrderItems- contains OrderItemsID, OrderID (which i need to be the same as the OrderID Just added) and ProductID(which needs to be taken from the list created and looped to make a record for each item in the "basket".
When you do
lastID = conn.execute("SELECT last_insert_rowid()")
lastID gets bound to an sqlite3.Cursor:
To retrieve data after executing a SELECT statement, you can either treat the cursor as an iterator, call the cursor’s fetchone() method to retrieve a single matching row, or call fetchall() to get a list of the matching rows.
The cursor cannot be converted automatically to the raw ID. You'll have to pull it out yourself, e.g. by doing something like
row = lastID.fetchone()
row_id = row[0]
Then use row_id in your query instead of lastID.

Appending to lists results from SQL

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.

Is there some way to save a mysql columns value in a python var?

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]

Fetching some values into variables

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

Categories

Resources