Fetching some values into variables - python

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

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.

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 a variable

I got this code:
cursor.execute('SELECT nom FROM productes WHERE listacompra = 1')
producteslc = cursor.fetchone()
The problem is that when I do print producteslc, it returns (u'Natillas',), when the value on the SQL Database is just Natillas.
What could I do to have a variable with value = Natillas? I'm trying to do some stuff with split but I'm not able to do it at my own.
Thank you
The result of fetchone is a tuple of the values of one row.
Since you only fetch a single column, the result is a tuple singleton: (u'Natillas',)
To get the string:
producteslc = cursor.fetchone()[0]
See: Tuples and Sequences in the doc
EDIT
To fetch several rows, you can use fetchall() function:
rows = cursor.fetchall()
for row in rows:
print(row[0])
To print each name.

Iterating over resultset with comparison of column name - in python with Mysqldb

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 == "..."):
...

Increment row MySql 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.

Categories

Resources