我在
hasInteracted
表中有一个整数列 Userdata
。
当我尝试时
cursor.execute("UPDATE Userdata SET hasInteracted = 1 WHERE chatid = ?", (chatid,))
该值未更新。 我对这一切都是新手,我错过了什么明显的事情吗?
完整代码:
import time
import logging
import sqlite3
from aiogram import Bot, Dispatcher, executor, types
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
TOKEN = "" #deleted for the question
connection = sqlite3.connect("database.db")
cursor = connection.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS Userdata (
chatid INTEGER PRIMARY KEY UNIQUE ON CONFLICT IGNORE,
hasInteracted INTEGER
)
''')
connection.commit()
#cursor.execute('CREATE INDEX idxChatid ON Users (chatid)')
#connection.commit()
#connection.close()
bot = Bot(token = TOKEN)
dp = Dispatcher(bot = bot)
chatid = 0
startbtn = InlineKeyboardButton(text = "start", callback_data = "startbtn")
btn2 = InlineKeyboardButton(text = "example decision", callback_data = "btn2")
startMessageKb = InlineKeyboardMarkup().add(startbtn)
async def startConsoleMessage(dp: Dispatcher):
print("start")
async def secondMessage(message: types.Message):
await message.answer(text = "make a decision", reply_markup = InlineKeyboardMarkup().add(btn2))
@dp.message_handler(commands = ['start'])
async def startMessageInline(message: types.Message):
await message.answer(text = "do you wish to start?", reply_markup = startMessageKb)
chatid = message.from_user.id
cursor.execute("INSERT OR REPLACE INTO Userdata (chatid) VALUES (?)", (chatid,))
connection.commit()
@dp.callback_query_handler(text = ["startbtn", "btn2"])
async def keyboardHandler(call: types.CallbackQuery):
if call.data == "startbtn":
await secondMessage(call.message)
if call.data == "btn2":
global chatid
await call.message.answer("decision made")
cursor.execute("UPDATE Userdata SET hasInteracted = 1 WHERE chatid = ?", (chatid,))
connection.commit()
connection.close()
if __name__ == '__main__':
executor.start_polling(dp, skip_updates = True, on_startup = startConsoleMessage)
我尝试通过 SQLite DB 浏览器手动更新它。当我运行代码时,它再次更新为 Null。尝试使用
cursor.execute("UPDATE Userdata SET hasInteracted = ? WHERE chatid = ?", (1, chatid))
一开始但结果是一样的。我需要的只是将 hasInteracted 更改为 1
似乎我在分配
global chatid
之前错过了message.from_user.id
,所以它没有正确更新