H
H
hey_umbrella2021-06-06 22:22:46
Python
hey_umbrella, 2021-06-06 22:22:46

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"))


The error itself is star = cursor.fetchone()[0]
TypeError: 'NoneType' object is not subscriptable

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-06-07
@hey_umbrella

> 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

Requirement: The photo column must be a primary key or at least have a unique index, otherwise the query will simply add a duplicate row.
IMPORTANT
f'SELECT star FROM stars WHERE photo = "{photo}"' - never do that! Especially if the input is from the user. This is a good way to get SQL injection.
Use placeholders, in order:
cursor.execute('SELECT star FROM stars WHERE photo = ?', (photo, ) )
or by name
cursor.execute('SELECT star FROM stars WHERE photo = :photo', {'photo' : photo} )
And more convenient and safer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question