我正在尝试将数据添加到表中,但它给了我一个错误sqlite3.IntegrityError: UNIQUE constraint failed: test.user_id
,我该怎么办?
编码:
from aiogram import Bot, types
from aiogram import md
import sqlite3
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
bot = Bot(token='token')
dp = Dispatcher(bot)
conn = sqlite3.connect('DataBase.db', check_same_thread=False)
cursor = conn.cursor()
def db_table_val(user_id: int, user_name: str, user_surname: str, username: str, user_nick: str):
cursor.execute('INSERT INTO test (user_id, user_name, user_surname, username, user_nick) VALUES (?, ?, ?, ?, ?)', (user_id, user_name, user_surname, username, user_nick))
conn.commit()
@dp.message_handler(content_types=['text'])
async def get_text_messages(message: types.Message):
if "+ник" in message.text:
await message.reply('Привет! Ваш ник добавлено в базу данных!')
args= message.text.split()
us_id = message.from_user.id
us_name = message.from_user.first_name
us_sname = message.from_user.last_name
username = message.from_user.username
db_table_val(user_id=us_id, user_name=us_name, user_surname=us_sname, username=username, user_nick=args[2])
elif message.text == "мой ник":
cur = conn.cursor()
cur.execute('SELECT user_nick FROM test WHERE user_id = ?', (message.from_user.id,))
one_result = cur.fetchone()
await message.reply(*one_result)
if __name__ == "__main__":
executor.start_polling(dp)
user_id 字段是受限制的(每行必须是唯一的)。该错误表明请求试图违反此限制,即 添加名称已在表中的用户。在执行 INSERT 之前,您需要检查是否已经存在具有该昵称的用户..