Answer the question
In order to leave comments, you need to log in
How to add +1 to a value in sqlite?
I need to add +1 to star after pressing the button, what's wrong?
if call.data == 'stars':
#ursor.execute(f'UPDATE stars SET star = star + 1 WHERE photo = "{photo}"')
#con.commit()
photo = call.message.text
con = sqlite3.connect("database.db")
cursor = con.cursor()
cursor.execute(f'SELECT star FROM stars WHERE photo = "{photo}"')
star = cursor.fetchone()[0]
con.commit()
cursor.execute(f'UPDATE stars SET star = star +1; WHERE photo = "{photo}"')
con.commit()
markup = telebot.types.InlineKeyboardMarkup()
markup.add(telebot.types.InlineKeyboardButton(text=f'Рейтинг - ⭐{star}', callback_data="stars"))
Answer the question
In order to leave comments, you need to log in
> The error itself is star = cursor.fetchone()[0]
> TypeError: 'NoneType' object is not subscriptable
not subscriptable means that you are trying to take an index from an object that does not support it. In your case, an object of type NoneType - i.e. None.
In other words, cursor.fetchone() returned None, and of course you can't take an index from None.
Why did fetchone() return None? Because the SELECT query didn't find any rows with a matching photo value!
How to solve it?
Insert a row with a photo into the table, and if it doesn't work (since such a photo already exists), then update it. There are two ways.
1. Code. Check what fetchone() returned. If None, then we do INSERT. If not None, then UPDATE.
2. Database tools, which is usually called UPDATE/INSERT, or UPSERT for short . For sqlite, this would require something like this:
INSERT INTO stars (photo, star) VALUES (photo id, 1) ON CONFLICT (photo) DO UPDATE SET star = star + 1
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question