D
D
d3m0l2021-09-20 18:47:50
Python
d3m0l, 2021-09-20 18:47:50

sqlite3.IntegrityError: UNIQUE constraint failed: users.user_id, what should I do?

conn = sqlite3.connect('db.db', check_same_thread=False)
cursor = conn.cursor()

def db_db_val(user_id: int, user_name: str, username: str):
    cursor.execute('INSERT INTO users (user_id, user_name, username) VALUES (?, ?, ?)',(user_id, user_name, username))
    conn.commit()



@bot.message_handler(commands=['db'])
def test(message):
   # try:
        bot.send_message(message.chat.id, 'test')
        if message.from_user.id in cursor.execute('SELECT user_id FROM users'):
            bot.send_message(message.chat.id, 'upd')

            cursor.execute(f'UPDATE users SET user_id = {message.from_user.id} WHERE user_id = {message.from_user.id}')
            cursor.execute(sql)
            conn.commit()

        else:
            bot.send_message(message.chat.id,'add')

            us_id = message.from_user.id
            us_name = message.from_user.first_name
            username = message.from_user.username

            db_db_val(user_id=us_id, user_name=us_name, username=username)
  #  except:
  #      bot.send_message(message.chat.id,'123')


adds to the database and update does not work, I don’t understand what the problem is, help me with

an error: sqlite3.IntegrityError: UNIQUE constraint failed: users.user_id

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-09-20
@Vindicar

message.from_user.id in cursor.execute('SELECT user_id FROM users')
Why do you need to select all users so that you can then use python to search for data in it? Use the WHERE keyword, and use prepared statement to substitute the value from the variable, not string formatting.
f'UPDATE users SET user_id = {message.from_user.id} WHERE user_id = {message.from_user.id}'
"If id = 1 then make id equal to 1". Who?!
And yes, don't use string formatting to form a query string . Use prepared statements.
For example like this:

ids = cursor.execute('SELECT user_id FROM users WHERE user_id = ?', (message.from_user.id,))

> I do not understand what the problem is
In the lack of knowledge of the basics of SQL , and in an attempt to write bots without understanding the basics.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question