Answer the question
In order to leave comments, you need to log in
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')
Answer the question
In order to leave comments, you need to log in
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,))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question