A
A
Anire19852021-02-22 17:21:17
Python
Anire1985, 2021-02-22 17:21:17

How to correctly compare data with a variable?

I need to read the data from a cell, add it to a variable, and then change the data only for those cells that are equal to the given variable. Everything was simple when it was necessary to compare numbers, with words the problem. Commas or brackets are written to the variable, and even after removing them, errors still occur.

import sqlite3
new_users2 = [
('Sem S', '1', 'r', 'p', '10.02.2010', ),
('Kim R', '3', 'r', 'p', '10.02.2010', )
]
con = sqlite3.connect(":memory:")
with con:
    c = con.cursor()
    c.execute('''CREATE TABLE brothers
    (id INTEGER PRIMARY KEY,
    name VARCHAR (30) NOT NULL,
    ves INTEGER NOT NULL,
    flag varchar(5) NOT NULL,
    status varchar(5) NOT NULL,
    last_date varchar (15))''')
    c.executemany('INSERT INTO brothers(name, ves, flag, status, last_date ) VALUES (?,?,?,?,?)', new_users2)
    for row in c.execute('SELECT * FROM brothers'): print(row)

c.execute("SELECT name from brothers;")
user = c.fetchone()  # то самое место которое вызывает ошибку
c.execute(f"UPDATE brothers SET ves=ves+500 WHERE name = {user};")


this is a cut from the main code

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
o5a, 2021-02-22
@Anire1985

First, fetchone returns a tuple, not a single value, i.e. to get the name, you need to take not user, but user[0]
Secondly, for queries with external values, instead of formatting a string, it is better to use parameter passing.

c.execute(f"UPDATE brothers SET ves=ves+500 WHERE name = ?", (user[0], ))

And in general, this code will change the value only for the records of the first user of the table selection.

R
Rsa97, 2021-02-22
@Rsa97

String values ​​in MySQL must be enclosed in quotation marks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question